Home > Software engineering >  Syntax related query during variable declaration and initialization
Syntax related query during variable declaration and initialization

Time:12-30

Consider the following code snippet

int main(){
 int a, b, c;
 printf("%d %d %d", a, b, c);
 return 0;
}

This is going to display some garbage value.
Now, consider this snippet.

int main(){
 int a, b, c = 0;
 printf("%d %d %d", a, b, c);
 return 0;
}

This displays 0 0 0 for every execution. But I've only initialized variable c to 0. Is this some shorthand for doing something like, int a=0, b=0, c=0;

Didn't know how to look for such doubt in official documentation.

CodePudding user response:

Without initialization, a, b are indeterminate right after int a, b, c = 0;

Their values are neither certainly consistent nor safe to access.

indeterminate value
either an unspecified value or a trap representation § C17dr 3.19.2

unspecified value
valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance 3.19.3

trap representation
an object representation that need not represent a value of the object type 3.19.4

If an initialization is specified for the object, ...; otherwise, the value becomes indeterminate each time the declaration is reached. 6.2.4 6


Didn't know how to look for such doubt in official documentation.

See Where do I find the current C or C standard documents? and search the spec for initialization.

CodePudding user response:

Well, a and b are getting garbage on both examples. The only difference is that their garbage are different on each execution. Like, they are put on an adress that can contain anything, as, -2130381 or 83943097 or even 0. X% of the times you can get a 0 on an unintialized value, and it will work on the first Y modifications of the code. After that, your code can just broke and you may spend some time debugging it.

  • Related