1

for example

static char all_data;

without initializing value to it. what is the default value? Or is it a Undefined Behavior?

I tried on my gcc-4.6 the answer is 0.

Thanks.

BufBills
  • 8,005
  • 12
  • 48
  • 90
  • 5
    it should be 0 as per C standard. – anishsane Dec 31 '13 at 05:29
  • For the `static char` it should be `0`; for a `static char *` however... – Elliott Frisch Dec 31 '13 at 05:32
  • 2
    @ElliottFrisch It's still 0 (which is not necessarily represented in memory as all 0 bits). – Jim Balter Dec 31 '13 at 05:40
  • @JimBalter, "which is not necessarily represented in memory as all 0 bits". Did not understand this. AFAIK, the static variables are zero'ed by `memset` (or something functionally similar to it). I don't know of a case, where any pointer may be NULL, but may have some of its bits set. – anishsane Dec 31 '13 at 05:45
  • 1
    @anishsane (the equivalent of) memset is only used in implementations where it can be (which includes all implementations you are familiar with). That you don't know of other implementations doesn't mean there are none; see http://c-faq.com/null/machexamp.html – Jim Balter Dec 31 '13 at 05:49

3 Answers3

9

Per C99:

If an object that has static 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;
— if it is a union, the first named member is initialized (recursively) according to these
rules.
tristan
  • 4,235
  • 2
  • 21
  • 45
3

According to C standard static variables are by default initialized to zero. But it's a good practice to always initialize it explicitly. In this link there is a para named "Initialization" you will find your necessary information there.

taufique
  • 2,701
  • 1
  • 26
  • 40
1

open-std.org: ISO/IEC 9899:TC2 tells us:

if an object that has static storage duration is not initialized explicitly, then ... if it has arithmetic type, it is initialized to (positive or unsigned) zero

(page 126)

The char type is an arithmetic type. You are guaranteed initialization to 0.

Darren Stone
  • 2,008
  • 13
  • 16