-2

I want to make all the variables which I create in my program to have initialization to zero without doing it explicitly. For example suppose if I create a variable like below:

int i;

We know that it must contain any garbage value and to make it have value 0 by default we need to declare it like

int i=0;

but I want my all variables in the program to contain garbage value as 0 not any other value.

In my code I want my every variables (which include class variables, global variables, local variables) to automatically initialize to 0 without doing it explicitly.

So what logic I tried is that in C, I have written the "Hello World" program without using main() function. So what I have done in that time is to override the _start function which is the first function called by compiler to set up everything and then call to main(). So I think there must be a function which compiler calls during the creation of a variables and I thought we can set the value 0 to the all variables there. Please help me with this problem. If there exist some other logic to solve this problem you can share with me I am open to all solutions but please don't say to explicitly declare them with the value 0.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vinay Kumar
  • 674
  • 2
  • 9
  • 21
  • 4
    It doesn't make sense to even discuss this without knowing the scope of the variable in the example. Local scope and file scope variables follow different rules - the latter have static storage duration, which is what matters here. – Lundin Oct 16 '20 at 08:21
  • In addition, it is _bad practice_ to rely on default initialization of static storage variables, with the exception of C++ classes, where you are _supposed_ to rely on it thanks to constructors. So overall, this question is too broad and unclear. You need to narrow it down to a specific use-case in a specific language and also state _why_ you need default initialization - what problem do you think that solves? – Lundin Oct 16 '20 at 08:26
  • 3
    *"I want to make all the variables which I create in my program to have initialization to zero without doing it explicitly."* May I ask why? These days a common code guideline suggests to restrict the scope of the variables as small as possible, declare them as const if not mutating and possibly avoid the pattern of initializing with a value and change it immediately after with the correct one. – Bob__ Oct 16 '20 at 08:33
  • 1
    even if you talk about variables in local scopes, automatically initializing them to 0 would be a bad idea, because what if the code is compiled without the option to initialize to 0 by another person? The only good idea is to init uninitialized variables to known special constants ([which some compilers do in debug mode to help debugging](https://stackoverflow.com/q/370195/995714)) – phuclv Oct 16 '20 at 09:04

2 Answers2

4

As a person who spends much of his working life looking at other people's broken code, I really have to say this, although I doubt it will be popular...

If it matters what the initial value of a variable is, then you should initialize it explicitly.

That's true even if you initialize it to what is, in fact, the default value. When I look at a statement like this:

int i = 0;

I immediately know (or think I know) that the programmer really thought about the value, and set it. If I read this:

int i;

then I assume that the programmer does not care about the value -- presumably because it will be assigned a value later.

So far as automatic variables are concerned, it would be easy enough for the compiler to generate code that zero'd the relevant part of the stack frame on entry to a function. I suspect it would be hard to do in application code; but why would you want to? Not only would it make the program behave in a way that appears to violate the language specifications, it would encourage slopping, unreadable programming practices.

Just initialize your variables, and have done with it. Or, if you don't want to initialize it because you know that the compiler will initialize it in the way you want, insert a comment to that effect. You'll thank yourself when you have to fix a bug five years later.

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
3

Default initialization and some words regarding the complexity of initialization in C++

To limit the scope of this discussion, let T be any kind of type (fundamental such as int, class types, aggregate as well as non-aggregate), and the t be a variable of automatic storage duration:

int main() {
    T t;  // default initialization
}

The declaration of t means t will be initialized by means of default initialization. Default initialization acts differently for different kind of types:

  • For fundamental types such as int, bool, float and so on, the effect is that t is left in an uninitialized state, and reading from it before explicitly initializing it (later) is undefined behavior
  • For class types, overload resolution resolve to a default constructor (which may be implicitly or implicitly generated), which will initialize the object but where its data member object could end up in an uninitialized state, depending on the definition of the default constructor selected
  • For array types, every element of the array is default-initialize, following the rules above

C++ initialization is complex, and there are many special rules and gotchas that can end up with uninitialized variable or data members of variables whence read results in UB.

Hence a long-standing recommendation is to always explicitly initialized you variables (with automatic storage duration), and not rely on the fact that default initialization may or may not result in a fully initialized variable. A common approach is (attempting) to use value initialization, by means of initialization of variable with empty braces:

int main() {
    int i{}; // value-initialization -> zero-initialization
    SomeAggregateClass ac{}; // aggregate initialization
}

However even this approach can fail for class types if one is not careful whether the class is an aggregate or not:

struct A {
    A() = default; // not user-provided.
    int a;
};

struct B {
    B(); // user-provided.
    int b;
};

// Out of line definition: a user-provided
// explicitly-defaulted constructor.
B::B() = default;

In this example (in C++11 through C++17), A is an aggregate, whereas B is not. This, in turn, means that initialization of B by means of an empty direct-list-init will result in its data member b being left in an uninitialized state. For A, however, the same initialization syntax will result in (via aggregate initialization of the A object and subsequent value initalization of its data member a) zero-initialization of its data member a:

A a{};
// Empty brace direct-list-init:
// -> A has no user-provided constructor
// -> aggregate initialization
// -> data member 'a' is value-initialized
// -> data member 'a' is zero-initialized

B b{};
// Empty brace direct-list-init:
// -> B has a user-provided constructor
// -> value-initialization
// -> default-initialization
// -> the explicitly-defaulted constructor will
//    not initialize the data member 'b'
// -> data member 'b' is left in an unititialized state

This may come as a surprise, and with the obvious risk of reading the uninitialized data member b with the result of undefined behaviour:

A a{};
B b{};     // may appear as a sound and complete initialization of 'b'.
a.a = b.b; // reading uninitialized 'b.b': undefined behaviour.
dfrib
  • 70,367
  • 12
  • 127
  • 192
  • Hy, everyone in comment section or in answer just telling me to explain this problem more specifically or not to try to do anything like it in my code where on the other side you just give very good explanation for handling that scenario instead of telling me not to do that. Yes your answer is not fully solved my problem but it gives me a brief of how it works and what can I do to solve this. Your code ```int i{}``` yes it initializes my variable to zero which is good but the class explanation you have given is not working as you have described it. – Vinay Kumar Oct 16 '20 at 18:38
  • Even if i make my class as aggregate class it still gives me garbage value. – Vinay Kumar Oct 16 '20 at 18:39