C ++ variable declaration

I am wondering this code:

int main(){
    int p;
    for(int i = 0; i < 10; i++){
      p = ...;
    }
    return 0
}

exactly coincides with the fact that

int main(){
    for(int i = 0; i < 10; i++){
      int p = ...;
    }
    return 0
}

in terms of efficiency? I mean, the variable p will be recreated 10 times in the second example?

+5
source share
4 answers
  • The same in terms of efficiency.
  • This is not the same in terms of readability. The second is better in this aspect, isn't it?

This is the semantic difference that the code hides because it makes no difference to int, but it matters to the human reader. Do you want to carry the value of any calculation that you do in an ...outside loop? You will not do this, so you must write code that reflects your intention.

- p, , , , "" - .

, , ,

/* p is only used inside the for-loop, to keep it from reallocating */
std::vector<int> p;
p.reserve(10);

for(int i = 0; i < 10; i++){
  p.clear();
  /* ... */
}
+9

. .

int , ( ) - ... .

, , - . , , , . , , . ( ) .

, , , :)

+4

- , . - .

Edit: this does not necessarily apply to user types, especially those related to memory. If you are writing a loop for any T, I would probably use the first form just in case. But if you know that it is a built-in type like int, pointer, char, float, bool, etc. I would go for the second.

+1
source

In the second example, p is displayed only inside the for loop. you cannot use it in your code. In terms of efficiency, they are equal.

0
source

All Articles