cancel
Showing results for 
Search instead for 
Did you mean: 

variable gets undefined behaviour out of the loop body

demir
Senior II

Hi,

I am writing C++ program on Visual Basic first, once it is compiled I will port it into STM32 Cube IDE environment. I wrote a simple for loop. When I run this code, I get very strange value for z out of the loop that is 1971940899.

You can see the terminal output as below.

 

when z is equal to 10, the loop will be broken out 5 when z is equal to 10, the loop will be broken out 6 when z is equal to 10, the loop will be broken out 7 when z is equal to 10, the loop will be broken out 8 when z is equal to 10, the loop will be broken out 9 when z is equal to 10, the loop will be broken out 1971940899

 

Could you please help me resolve ?

Thanks.

for(int z=5;z<15;z++) { cout<<"when z is equal to 10, the loop will be broken out\n"; if(z==10) { break; } cout<<z<<endl; } cout<<z<<endl;

 

1 ACCEPTED SOLUTION

Accepted Solutions

Because it's out-of-scope, and may be a register or stack variable

{ // SCOPE A int z; for(z=5;z<15;z++) { // SCOPE B cout<<"when z is equal to 10, the loop will be broken out\n"; if(z==10) { break; } cout<<z<<endl; } // END SCOPE B cout<<z<<endl; } // END SCOPE A
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

1 REPLY 1

Because it's out-of-scope, and may be a register or stack variable

{ // SCOPE A int z; for(z=5;z<15;z++) { // SCOPE B cout<<"when z is equal to 10, the loop will be broken out\n"; if(z==10) { break; } cout<<z<<endl; } // END SCOPE B cout<<z<<endl; } // END SCOPE A
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..