s.paszko
s.paszko

Reputation: 732

Difference between variable declared at the top of a function and one declared later

What is the difference in generated code when I have the definition of a variable at the top of a function and when I have it declared later. Example:

int f(int parameter) {
 int a = parameter * 2;
 if (a == 4) 
  return 1;
 int b = parameter * 4;
 if (b == 4) 
  return 2; 
 return 0;
}

Does output code have b variable initialization and allocation after if (a == 4) or will a and b variables be initialized at the same moment?.

Upvotes: 1

Views: 141

Answers (1)

To see what actually happens, look at the generated assembler.

In terms of allocating space, most compilers will allocate enough space on the stack for all the variables used in a function at the start of the function. (This doesn't have to happen like this, but I don't know of any compiler which don't work like this.)

In terms of initializations, the abstract machine (as defined by the C and C++ standards) treats the initializations (that is, setting the initial values) as happening at different times. b is initialized after the comparison of a with 4.

Of course, by the as-if rule, if the initialization doesn't have side-effects, the compiler can move the initialization round as it sees fit. This happens more often with C than with C++, because C++ initializers often involve constructors in other translation units, and the compiler can't see if there are side effects there.

In this simple case if you optimize, it is quite likely that both a and b will only ever be stored in a register, and this may well be the same register. (This is because you are using plain int variables, and because you don't overlap the use of a and b.)

Upvotes: 7

Related Questions