This seems like a simple problem, but it is not intuitive to me.
Say you have a loop like this:
int i;
for(i=0;i<10;i++){
float b = 25.2;
float c;
c=b+i;
}
Is there any negative consequences to defining b as float in every single loop? I thought it would have, but I am not so sure because I’ve seen code that works with this…
Thanks…
This is perfectly ok, and in fact I don’t think it matters one bit in any decent compiler, if you only use the
floatinside the loop.It does make sense for code clarity to put it in the loop, but it’s a matter of taste mostly.
But beware for situations like
I’ve seen similar situations not generate compiler warnings, which makes for hard to trace bugs.
edit just tested,
gccdoes compile differently, but with-O3the generated assembly is identical. Test withgcc -S file.c. Update:-O1is enough, and it actually depends on the order you declare variables. If thefloatwas declared belowint i;in your example, the compiled assembly will still be identical.