1

I want to know the properties of initializing array once in global scope and once in the function scope.

Let say:

char arr[4];

int main() {
    .....
}

What will be the values in this array?

What with this option:

int main() {
    char arr[4];
    ....
}

Is there any difference in the last case with this:

int main() {
    ....
}

int func1() {
    char arr[4];
    ....
}

Will the result change in different compiler? Thank

babushka
  • 45
  • 4
  • 6
    (1) zeros (2) indeterminate (3) no. – n. m. could be an AI Dec 24 '17 at 22:15
  • Variables declared in function blocks will go out of scope when the function ends. – t0mm13b Dec 24 '17 at 22:16
  • checkout some [function scope](http://www.tutorialspoint.com/cprogramming/c_scope_rules.htm) tutorials online – JoshKisb Dec 24 '17 at 22:17
  • At the level of detail of this question, there is no difference between C90 and either pre-standard C or C99 or C11. There are differences in other array initialization contexts (designated initializers, function calls in local array initializers, etc), but for this much, there's no difference. Note that some platforms may appear to initialize local arrays to zeros, especially if they're in `main()`, but you cannot rely on that — the values are indeterminate. – Jonathan Leffler Dec 24 '17 at 23:55

1 Answers1

3

In a well-mannered system, the file-scope array will be initialized to all zeros. The in-function array is less predictable; chances are high that it'll just inherit whatever scrud was on the stack at the time.

In general, it's probably safe to assume that any modern tool chain compiling for a desktop system will be "well-mannered", but if it's for an embedded system you may want to check for yourself whether the bss section gets initialized to all zeros. That initialization is part of the processor (or sometimes board) specific support package, and you can't always trust that it's been done.

Tim Wescott
  • 478
  • 4
  • 14
  • 4
    Zero-initialization of static-lifetime variables is mandated by the standard, not a matter of QoI. – Quentin Dec 24 '17 at 22:23
  • 2
    Dunno what you mean by "Qol", but I've worked with plenty of little tool chains that didn't bother to follow the standards, or that were cut off at the knees by some individual developer that hijacked the initialization code. Standards are wonderful things, but they're like speed limits -- you can't trust individuals (or even companies who make processors) to adhere to them. – Tim Wescott Dec 25 '17 at 04:44
  • 1
    QoI = quality of implementation. An implementation that only is C90 in 2017 probably shouldn't be trusted for following standards. – Jens Gustedt Dec 25 '17 at 08:40