0

I learnt that all the global variables will be initialized to '0'. As per this if we declare the below line globally,

static char *pointer;

pointer should be equal to NULL. But is this always true? Because in my current project, I initialized a pointer like this. But when I compared pointer == NULL, it is becoming false and it is already assigned a value. Is it some junk address?

Jens
  • 69,818
  • 15
  • 125
  • 179
kadina
  • 5,042
  • 4
  • 42
  • 83
  • 2
    [yes it will](http://stackoverflow.com/a/21964142/1708801) – Shafik Yaghmour Jun 18 '15 at 20:42
  • Yes it is always initialised to 0. Please show your full code if you want an explanation of the latter part of your question. I'm pretty certain there will either be a bug in your code or an incorrect interpretation of the results. – kaylum Jun 18 '15 at 20:44
  • 1
    by convention it will, but it's a good habit to set it to 0 or NULL by default to avoid confusion, as it's common to forget this and think it is initialized to whatever value was in that memory address, and cause doubt. – Dmytro Jun 18 '15 at 20:44
  • Which compiler are you using? – Theodoros Chatzigiannakis Jun 18 '15 at 20:45
  • 1
    There's something wrong with your environment's C startup if the pointer has junk in it (this can happen on embedded systems where the people setting up the development environment didn't know what they were doing) – M.M Jun 18 '15 at 21:49

1 Answers1

4

All objects with static storage duration (global or not) will be implicitly initialized to 0 or NULL if no explicit initializer is given.

Chapter and verse:

6.7.9 Initialization
...
10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
John Bode
  • 119,563
  • 19
  • 122
  • 198