0

I'm new to C, this is My code. Maybe this is too easy for someone else.

#include <stdio.h>
int main()
//Assign value to identifiers
{
    int a,b,c,d=6;
    printf("a:%d\n",a);
    printf("b:%d\n",b);
    printf("c:%d\n",c);
    printf("d:%d",d);
    return 0;
}

Why is a=16, b=0, and c=12522400?

a:16
b:0
c:12522400
d:6
kile
  • 141
  • 1
  • 7
  • 1
    By chance. Values of uninitialized non-static local variables are indeterminate. If you want to know the reason of this specific result, you will need deep inspection of generated code and some other information of your environment. – MikeCAT Oct 30 '20 at 23:45
  • 1
    Maybe take a look at this: https://stackoverflow.com/questions/6838408/how-can-i-declare-and-define-multiple-variables-in-one-line-using-c – mzndr Oct 30 '20 at 23:45
  • 1
    What value did you expect them to have? – klutt Oct 30 '20 at 23:48
  • Try `int a=6, b=6, c=6, d=6;` instead. – L. Scott Johnson Oct 30 '20 at 23:51
  • @klutt I expect them all to be 6. – kile Oct 30 '20 at 23:57
  • That's not the way initializers work; only `d` has an initializer — the other variables are uninitialized and therefore contain indeterminate values. See C11 [§6.7.9 Initialization](http://port70.net/~nsz/c/c11/n1570.html#6.7.9) and [§6.7 Declarations](http://port70.net/~nsz/c/c11/n1570.html#6.7) in general, especially the first section which gives the grammar for declarations. – Jonathan Leffler Oct 31 '20 at 01:29
  • The syntax shown is equivalent to this: `int a; int b; int c; int d = 6`. The declarators `a`, `b`, `c` and `d` are completely independent. Only the `d` declarator has an initializer: `d = 6`. The initializer does not work "across" the other declarators. It is a child of the `d` declarator only. – Kaz Oct 31 '20 at 01:34

1 Answers1

1

Because those variables are not initialized. You always have to initialize a local, automatic variable to avoid undefined behaviour.

For more details look here: https://en.wikipedia.org/wiki/Uninitialized_variable

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
kurta999
  • 60
  • 8