开发者

value of allocated array not initialized

开发者 https://www.devze.com 2023-03-03 05:24 出处:网络
If I have: int array[20]; What is the value of array[0] if nothing has been initialized there yet? Is there a way to check if it has been initialized?开发者_运维技巧\"...suppose I have...\" You hav

If I have:

int array[20];

What is the value of array[0] if nothing has been initialized there yet? Is there a way to check if it has been initialized?开发者_运维技巧


"...suppose I have..." You have it where?

If you have something like this in namespace scope, then it is an object with static storage duration, which is always zero-initialized.

If you have something like this in local scope, then it is an object with automatic storage duration, which is not initialized at all. The value of array[0] is unpredictable. And no, there's no way to tell whether something has been deliberately initialized or not.


What is the value of array[0] supposing nothing has been initialized there yet?

It depends whether the array is defined in the file scope or in the function scope. In function scope array elements would contain unspecified values whereas in file scope they would be zero initialized.


It's basically garbage or whatever value was in that particular memory spot. You can't detect if it's been initialized no.


It will be in so-called indeterminate state, which on most implementations means whatever was in that memory at the moment memory was occupied by the array - that's typically called garbage.


It's undefined, depends on the compiler and release flavour : some compiler will fill it with a pattern in debug, but won't do it in release. In any case, relying on the compiler and trying to check it instead of properly initializing is a bad practice and will probably lead you to major issues.


Is there a way to check if it has been initialized?

There's no need to check.Unless you explicitly initialize it, it stays uninitialized.

0

精彩评论

暂无评论...
验证码 换一张
取 消