0

I heard that we should make variables as local as possible, I agree. Consider this code:

int main()  {
    for(int i = 0; i<5; ++i)    {
        int temp;
        std::cin >> temp;
        std::cout << temp << std::endl;
    }
    return 0
}

temp is the local variable of the for loop. However, I am afraid that temp is declared at every loop, therefore make the program run slower. Would it be better to avoid this case and declare the temp outside the for loop?

int main()  {
    int temp;
    for(int i = 0; i<5; ++i)    {
        std::cin >> temp;
        std::cout << temp << std::endl;
    }
    return 0
}
an offer can't refuse
  • 4,245
  • 5
  • 30
  • 50
  • 5
    That doesn't make any difference on speed, except that you put `temp` on the stack for longer time in the latter case. I'd prefer the first one. – Nawaz Oct 06 '16 at 16:23
  • Who gives a hoot if it's slower? Using C++ made your program slower, you should be programming hand-tuned assembly! – GManNickG Oct 06 '16 at 16:25
  • @GManNickG That's my personal understanding, I thought with a more step `declaration` will make the program run slower. – an offer can't refuse Oct 06 '16 at 16:28
  • That's a question best answered with a benchmark. – krzaq Oct 06 '16 at 16:32
  • 1
    @buzhidao: I was being facetious. You should focus on readability over performance. Even if this variable location made things slower, it makes things easier to read so it's worth it. Your program doesn't need to be as fast as possible, it just needs to be fast enough. After your program isn't fast enough, use a profiler to figure out where it's slow. Guaranteed it's not at this line. – GManNickG Oct 06 '16 at 16:36

3 Answers3

6

That doesn't make any difference on speed, except that you put temp on the stack for longer time in the latter case.

I'd prefer the first one, as it is a good practice to minimize the scope of variables wherever possible.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
2

Firstly, always write for clarity first and speed second. Secondly, don't comprise clarity for speed until you have measurements to show it helps.

Declaring a variable is a thing that happens at compile time. What happens at run-time is initialization, and yes, if you declare temp inside the loop, it will be initialized every time through the loop. This can matter if temp is expensive to initialize. However in the case of an int without an initializer, the cost is zero; the value is left indeterminate.

0

It's really a matter of personal preference. Declaring temp inside the for loop won't make a difference in speed.