c - Is there a difference between initializing a variable and assigning it a value immediately after declaration? -


assuming purely non-optimizing compiler, there difference in machine code between initializing variable , assigning value after declaration?

initialization method:

int x = 2; 

assignment method:

int x; x = 2; 

i used gcc output assembly generated these 2 different methods , both resulted in single machine instruction:

movl    $2, 12(%esp) 

this instruction sets memory held x variable value of 2. gcc may optimizing because can recognize end result of operations; think way interpret 2 versions. reasoning both version same thing: set part of memory specific value.

why distinction made between terms "initialization" , "assignment" if resulting machine code same?

is term "initialization" used purely differentiate variables have specific value assigned on (non-initialized) variables have whatever garbage value left in memory?

the behavior must identical, differences in generated code depend on compiler.

for example, compiler generate initialized variable:

somefunction: pushl    %ebp movl     %esp, %ebp pushl    $2 ; allocate space x , store 2 in ... 

and uninitialized, later assigned variable:

somefunction: pushl   %ebp movl    %esp, %ebp subl    $4, %esp ; allocate space x ... movl    $2, -4(%ebp) ; assign 2 x ... 

the c standard not mandate generated code identical or non-identical in these cases. mandates identical behavior of program in these 2 cases. , identical behavior not imply identical machine code.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -