Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c - Is the value of an un-initialialized variable aways 'garbage'?

Are there cases where it's ok to use a variable when it has not been initialized, or is it always assumed to be garbage? For example, one case would be:

// global example?
// static example?
// extern example?
// etc.
{
    int n=1, max_n;
    printf("%d %d
", n, max_n);
}

In this case max_n has a garbage/undefined value. But are there ever cases where the value is known and can be used, such as doing something like bool item being auto-initialized to 0/false, or is that never the case in C?

question from:https://stackoverflow.com/questions/65864682/is-the-value-of-an-un-initialialized-variable-aways-garbage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

By definition, if something is not initialized, it does not have a defined value. If it does have a defined value, it is initialized.

From cppreference:

The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea. It has to be initialized with a value before you can use it.

Also from cppreference about implicit initialization:

If an initializer is not provided:

  • objects with automatic storage duration are initialized to indeterminate values (which may be trap representations)
  • objects with static and thread-local storage duration are zero-initialized

So for example, int a; will be zero-initialized if declared in e.g. global scope, as a static class variable, as a thread_local variable, etc. In other cases, it will be uninitialized.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...