Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is zero-initialization not the default for non-initialized variables in c++? Is there a compiler option to force it?

Tags:

c++

In most languages I know, scalar-type variables are zero-initialized by default, if they were not initialized in the code. Why doesn't this happen in c/c++? The only reason I could think of is performance, but

  • is it really that performance-consuming, if I do initialize it?
  • is it preferable to have undefined behavior?
  • if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

Wouldn't it be easier to explicitly tell the compiler somehow not to zero-initialize a variable, if this might be a performance issue?

An finally my question: Is there a gcc option to tell the compiler to zero-init by default?

like image 963
Ben Avatar asked Apr 03 '19 13:04

Ben


People also ask

Why do we initialize variables to 0 in C?

In C programming language, the variables should be declared before a value is assigned to it. In an array, if fewer elements are used than the specified size of the array, then the remaining elements will be set by default to 0. Let us see another example to illustrate this.

Which variable is initialized to zero by compiler?

Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.

What happens when you don't initialize a variable in C?

Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is assigned a memory location by the compiler, the default value of that variable is whatever (garbage) value happens to already be in that memory location!

What is the default value of an uninitialized variable?

INTRODUCTION: An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using.


1 Answers

One of the founding principals of c++ is to not force developers to pay for what they don't use. If you write something like int x; x = 1; then you shouldn't have to pay for the zero initialization of x, even if that cost happens to be very tiny.

Edit : Regarding your other two points

is it preferable to have undefined behavior?

Undefined behavior is not necessarily a bad thing to have in the language (you can argue both ways). It's definitely a bad thing if you write code that causes it. Notably it gives more freedom to implementers and enables important optimizations.

if I want to avoid undefined behavior, I have to initialize it anyway, so what did I win?

It's not undefined behavior to have an uninitialized variable. It's undefined behavior to try to read from one.

like image 65
François Andrieux Avatar answered Oct 20 '22 21:10

François Andrieux