Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the value of i == 0 in this C++ code? [duplicate]

I am confused about the following code:

#include <iostream>

int i = 1;
int main()
{
    int i = i;
    std::cout << "i: " << i << "\n";
    return 0;
}

Output:

i: 0

I had expected running the above code would print 1. Can someone please explain the reason for this strange behavior?

like image 459
Ren Avatar asked Mar 20 '16 14:03

Ren


People also ask

What is I 0 in C programming?

Since in C an int can be interpreted as a boolean using a zero/non-zero rule (zero means "false", anything else means "true") the loop is going to continue until a break statement is reached inside the loop's body. You can rewrite the same loop as for (i=0; ;i++)

What is the value of i in C++?

cpp:13:13: Variable 'i' is uninitialized when used within its own initialization: given by a reasonable compiler may be a hint as to the problem. Perhaps jam up your warning levels and heed their advice. When you assign int i= i;, i gets initialized with the value of i which you just declared, hence an undefined value.

Why is my function not returning a value C?

In C there are no subroutines, only functions, but functions are not required to return a value. The correct way to indicate that a function does not return a value is to use the return type "void". ( This is a way of explicitly saying that the function returns nothing. )


1 Answers

You are initializing i with itself. The both i's in int i = i; are the inner one not the outer one. This is undefined behavior and you may get 0 or anything may happen.

This is the right way if you want to assign the outer i to the inner i.

#include <iostream>

int i = 1;
int main()
{
    int i = ::i;
    std::cout << "i: " << i << "\n";
    return 0;
}

Live Demo


BTW, You should carefully read all the compiler warnings. If you did you could see the problem yourself:

warning 'i' is used uninitialized in this function

like image 182
Humam Helfawi Avatar answered Oct 11 '22 16:10

Humam Helfawi