-4

I have question 'Why are global variables always initialized to 0?'. And I found the answer here.
Why are global variables always initialized to '0', but not local variables?

However, I have a new question.
Why C standard defined that the global variables should be initialized to 0? Why don't they initialize it to another number?(1, 2, 3...)

K1A2
  • 3
  • 2
  • The top answer of linked question already says why: efficiency – Jorengarenar Sep 18 '21 at 16:28
  • 3
    Does this answer your question? [Why are global variables always initialized to '0', but not local variables?](https://stackoverflow.com/questions/14049777/why-are-global-variables-always-initialized-to-0-but-not-local-variables) – Chris Sep 18 '21 at 16:29
  • Can you please clarify why the answers to the previous question don't resolve this? Note that this isn't really about the "C standard" per se; this behavior was well established in the C language long before there was an ANSI or ISO standard for it, and the standard merely codified existing practice. But the reasons given in the other answer (efficiency) are surely what motivated the language's original designers. – Nate Eldredge Sep 18 '21 at 17:00
  • `0` works for `int`s, for `double` for `char*`, for `struct whatever`, for `float [100]`, ..., ... – pmg Sep 18 '21 at 17:08
  • You ask a question, say you have found an answer, then ask the _same_ question. What exactly are you asking? Perhaps why zero and not some other value? That is a slightly different question and you should make it clear. – Clifford Sep 18 '21 at 17:31
  • @Clifford I edited question. I think my english skill is not enough to post the question. – K1A2 Sep 19 '21 at 01:15

1 Answers1

1

For all built in data types, zero is represented by a sequence of zero-value binary digits. Regardless of the width of the data type, all zeros, resolves to an arithmetic value of zero. The runtime start-up code does not zero-initialise individual variables, rather it zeros the entire block of memory in which the variables are instantiated.

By using zero, all float, double, int, char etc. have a value that can be compared to literal zero (0) and match. If you initialised with any other byte value (remember the block not the variables are initialised) the effective variable value would depend the data type (its width and representation).

Moreover zero-initialisation ensures that all pointers have a value NULL rather then some arbitrary and meaningless and possibly invalid address that would cause undefined behaviour if dereferenced.

Clifford
  • 88,407
  • 13
  • 85
  • 165