If we have the following 2 snippets of code in c++ that do the same task:
int a, b=somenumber;
while(b > 0)
{
a = b % 3;
b /= 3;
}
or
int b=somenumber;
while(b > 0)
{
int a=b%3;
b /= 3;
}
I don’t know much about computer architecture/c++ design, but i think that the first code is faster because it declares the integer a at the beginning and just uses it in the while-loop, and in the second code the integer a is being declared everytime the while-loop starts over. Can some one help me with this, am i correct or what and why ?
The int declaration is information for the compiler and does not translate to an instruction that has to be coded. So it makes no difference. Declaring the int inside the loop will not slop the loop down. Why not try compiling both for yourself and get the compiler to output assembly code so you can see for yourself.