Default variable value

2018-12-31 22:03发布

If I don't assign a value to a variable when I declare it, does it default to zero or just whatever was previously in the memory?

e.g.

float x;

标签: c++ c
8条回答
几人难应
2楼-- · 2018-12-31 22:30

It depends. If this is a local variable (an object with automatic storage duration) it will be uninitialized, if it is a global variable (an object with static storage duration) it will be zero initialized. Check also this answer.

查看更多
初与友歌
3楼-- · 2018-12-31 22:32

C++ does not instantiate variables. The value of x is whatever happened to be in the memory at the time. Never assume anything about its initial value.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 22:34

It depends on the lifetime of the variable. Variables with static lifetime are always zero-initialized before program start-up: zero-initialization for basic types, enums and pointers is the same as if you'd assigned 0, appropriately converted to the type, to it. This occurs even if the variable has a constructor, before the constructor is called.

查看更多
呛了眼睛熬了心
5楼-- · 2018-12-31 22:39

It can be compiler specific but generally release builds don't initialise variables to any particular value, so you get whatever is left in memory. Certain magic numbers are used in debug builds by some compilers to mark specific areas of memory however.

查看更多
高级女魔头
6楼-- · 2018-12-31 22:45

This depends on where you declare it. Variables in the global scope are initialized with 0, and stack-variables are undefined.

查看更多
情到深处是孤独
7楼-- · 2018-12-31 22:52

Using the value of any variable prior to initialization (note that static-storage-duration objects are always initialized, so this only applies to automatic storage duration) results in undefined behavior. This is very different from containing 0 as the initial value or containing a random value. UB means it's possible that anything could happen. On implementations with trap bits it might crash your program or generate a signal. It's also possible that multiple reads result in different unpredictable values, among any other imaginable (or unimaginable) behavior. Simply do not use the value of uninitialized variables.

Note: The following was edited based on comments:

Note that code like this is invalid unless you can assure that the type foo_t does not have padding bits:

foo_t x;
int i;
for (i=0; i<N; i++) x = (x<<1) | get_bit();

Even though the intent is that the "random value" initially in x gets discarded before the loop ends, the program may invoke UB as soon as it accesses x to perform the operation x<<1 on the first iteration, and thus the entire program output is invalidated.

查看更多
登录 后发表回答