Skip to main content
Senior
March 29, 2024
Solved

variable gets undefined behaviour out of the loop body

  • March 29, 2024
  • 1 reply
  • 1006 views

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;

 

This topic has been closed for replies.
Best answer by Tesla DeLorean

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

1 reply

Tesla DeLorean
Tesla DeLoreanBest answer
Guru
March 29, 2024

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 (See Profile) Up vote any posts that you find helpful, it shows what's working..