Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ variable declaration

Tags:

c++

Im wondering if this code:

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

is exactly the same as that one

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

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

like image 473
swan Avatar asked May 08 '10 12:05

swan


1 Answers

  • It's is the same in terms of efficiency.
  • It's not the same in terms of readability. The second is better in this aspect, isn't it?

It's a semantic difference which the code keeps hidden because it's not making a difference for int, but it makes a difference to the human reader. Do you want to carry the value of whatever calculation you do in ... outside of the loop? You don't, so you should write code that reflects your intention.

A human reader will need to seek the function and look for other uses of p to confirm himself that what you did was just premature "optimization" and didn't have any deeper purpose.

Assuming it makes a difference for the type you use, you can help the human reader by commenting your code

/* 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();
  /* ... */
}
like image 53
Johannes Schaub - litb Avatar answered Sep 30 '22 00:09

Johannes Schaub - litb