0

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;

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

taurus05
  • 2,491
  • 15
  • 28
  • 1
    The values of `a` and `b` are indeterminate in both versions. It's just by accident that they're being set to `0` in the second one. The compiler might be using an optimization when initializing `c` that happens to fill the whole block of memory with zeroes. – Barmar Dec 30 '22 at 02:26
  • 1
    Just because the values are indeterminate it doesn't mean they have to be garbage. They can be anything, including zero.. – Barmar Dec 30 '22 at 02:27
  • @Barmar, that means even though `a`, `b` are being initialized to `0`, that is still garbage value? – taurus05 Dec 30 '22 at 02:29
  • 3
    They have to contain something. 0 is just as good as anything else. – Barmar Dec 30 '22 at 02:31
  • To understand what's happening, you should really look at the assembly code. To request the assembly code from gcc, use the `-S` option. Or better yet, step through the assembly with a debugger. – user3386109 Dec 30 '22 at 03:13

2 Answers2

3

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

Their values are neither certainly consistent (they could be random) nor safe to access.

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

indeterminate value
either an unspecified value or a trap representation 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


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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

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 address that can contain anything, as, -2130381 or 83943097 or even 0. X% of the times you can get a 0 on an uninitialized 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.

taurus05
  • 2,491
  • 15
  • 28
Bitenco
  • 11
  • 1
  • 3