+ 2
Why i value different in this code??
13 Réponses
+ 5
There are two different variables named i in your code. The first one is declared in line 5 and local to main(). As you didn't initialize it, it will have some arbitrary garbage value (here: 8, but it might be any value like 0, 42 or 5354037).
The other variable i is declared in line 6 and is only valid within your for loop. Note that your for loop ends with a semicolon, so it is an empty loop. It's the same as for(int i=0;i<7;i++) {} <<== empty bracelets without any statements in between. Your for loop doesn't use or change the outer variable i.
In line 7, you print the value of the variable that was declared in line 5.
+ 6
Mustafa Coder
Local variables except static ones are not initialized to a default value. You can prove this by yourself, just insert a line under declaration of <i> at line 5, and print value of <i>. As Anna said, you will have arbitrary garbage value which is unpredictable in variable <i>.
+ 6
Mustafa Coder , nope. If you declare an uninitialized variable outside of a function, it will be set to 0. Within a function, it can have any arbitrary value.
int f; // uninitialized outside function, will be 0
int main() {
int i; // unitialized within function, indeterminate value
}
+ 5
I just ran the very same code you posted on Ubuntu (compiled with GCC) and got a "warning: ‘i’ is used uninitialized in this function [-Wuninitialized]" and the output was 0.
+ 4
Mustafa Coder try to name the variable in the loop different than i ex: j and you will have the same output "8"
+ 4
Anna sorry, in the begining I didnt understand your answer, but now I understood what you meant.
thanks alot
+ 3
zahraa 🇱🇧
No, that's not right.
Last value for i is 7
because the condition of for loop is less than 7 not equal to 7.
Thanks alot sister.
+ 3
Mustafa Coder yes i realized that so i detete the comment, you're welcome
+ 3
zahraa 🇱🇧 No problem, thank you to feedback
You are welcome too.
+ 2
Anna
Intial value of every variable is 0 when we dont give it value, you can check it again and see its output.
+ 2
zahraa 🇱🇧
What is the goal of that?
Surely, that's result same output.
+ 2
This verifies the idea of Anna
int main() {
int i;
for(int j=0;j<7;j++);
cout<<i;
return 0;
}
Then the output must be 0 since as you say above Mustafa Coder initially i is zero and no thing happened to change the value of i but in fact the output will be 8
+ 2
zahraa 🇱🇧 why the output will be 8?