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?
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++)
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.
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. )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With