What is the default state of variables?

When program C starts and variables are assigned to memory cells, does the standard C mean if this value is initialized?

// global variables int a; int b = 0; static int c; 

In the above code, "b" will be initialized to 0. What is the initial value of "a"? Is "c" any other since it is static for this module?

+4
source share
5 answers

Since you specifically specify global variables: in the case of global variables, whether they are declared static or not, they will be initialized to 0.

Local variables , on the other hand, will be undefined (if they are not declared static , in which case they will also be initialized to 0 - thanks Tyler McHenry). Translated, this means that you cannot rely on them containing any particular thing - they will simply contain what was already written in memory in this place, no matter how random garbage is in it, which may differ from run to run.

+11
source

Edit: Below, only local variables are applicable - not global.

The initial value of the variable is undefined. In some languages, a variable location in memory has zero value when declared, but in C (and C ++) an uninitialized variable will contain any garbage that lives in that place at that time.

Therefore, the best way to think about the fact that an uninitialized variable most likely contains garbage and has undefined behavior.

+5
source

a will be zero, and c also if they are global and not explicitly initialized. This is also true for local static variables.

Only local non-static variables are not initialized. Also, memory allocated using malloc is not initialized.

See here for initialization and distribution rules in C for different objects.

+4
source

I type too slowly this morning. Three people logged in quickly when I replied, so I deleted most of my message. The link I found was clear and concise, so I post it anyway: Wikipedia is an “uninitialized variable” to discuss the main issues.

+1
source

A quick test shows that a and c are 0.

 int a; static int c; int main() { printf("%d %d\n", a, c); return 0; } 

The location (and c) is determined at compile time; that is, they are not pushed onto the stack or into the memory interval returned by malloc. I think the C standard says that in all cases they are initialized to 0.

I am 99.9% sure about c and 98% sure about a . The static , in the context of global variables, is really similar to private in (say) C ++ and Java: it's about visibility, not about the location of the repository.

What Andrew Hare says about uninitialized variables is true for data stored on the stack or in malloc'd memory. Not so for statically stored variables.

0
source

Source: https://habr.com/ru/post/1286342/


All Articles