Effectiveness of the variable declaration C

advertisements

This question already has an answer here:

  • How is conditional initialization handled and is it a good practice? 5 answers

How long does it take to declare a variable in C, for example int x or unsigned long long var? I am wondering if it would make my code any faster in something like this.

for (conditions) {
    int var = 0;
    // code
}

Would it be faster to do this, or is it easier not to?

int var;
for (conditions) {
    var = 0;
    // code
}

Thanks for the help.


Whenever you have a question about performance, the best thing to do is wrap a loop around it (millions of iterations) and time it. But, in this case, you will likely find that it makes no difference.

It is more important to properly express the intentions of your code. If you need the variable outside your loop, delare it outside. If you only need the variable inside the loop, declare it inside.

You should always declare and initialize variables in narrowest scope possible.

You shouldn't be worrying about those types of micro-optimizations anyway (except in the rarest, rarest of cases). If you really need to worry about potential nano-second performance improvements, measure the difference. It is very unlikely that your variable declarations will be the largest bottleneck in your application.