Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++14 value initialization issue

Tags:

c++

c++11

c++14

Who knows wy local i_local value is zero-initialized in this example http://ideone.com/Cqer9Z?

#include <iostream>
using namespace std;

int main() {

    int i_local; // automatic storage duration, not static

    cout << "Value of i_local: " << i_local << endl; // (2-3) value is undetermined
}

It is variable with automatic storage duration and according to standart is should have undetermined value.

In my local computer (c++11) it is undetermined but in ideone (c++14) zeroed.

like image 885
zim32 Avatar asked Jan 09 '23 13:01

zim32


2 Answers

In full, the standard says (emphasis added):

When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.18). [...] If an indeterminate value is produced by an evaluation, the behavior is undefined except [in some irrelevant cases...]

You have undefined behaviour. It could print 0, it could print 50, it could print gibberish, or it could wipe your hard drive.

like image 61
Joseph Mansfield Avatar answered Jan 12 '23 17:01

Joseph Mansfield


Zero is one of the values of int, therefore it's perfectly legal for an int of undetermined value to be zero.

Furthermore, it's UB to even attempt to read that integer, so the value you see is by definition meaningless.

like image 44
Puppy Avatar answered Jan 12 '23 19:01

Puppy