0

I have only started learning coding recently, and am trying to grasp how for loops and while loops work. I was playing around with the following code, and was puzzled to find out that the output of the code was "hi". I thought the output of this code would have been "no" because the variable x would only continue to increase in value from 30 to 46 to 54 etc. until the parameter a is less than 1. So, I was hoping someone could point out where I went wrong with my reasoning, thank you so much!

int x = 30;
    for (int a=16;a>=1;a/=2)
        while((x!=14)){
            x += a;
        }
    if (x==14){
        cout << "hi" << "\n";
    }
    else
        cout << "no" << "\n";
  • This program exhibits undefined behavior by way of integer overflow. In practice, `x` grows very large, overflows, wraps around to a large negative integer, and eventually makes its way back to `14`. Basically, adding 16 enough times to cause the overflow is equivalent, on a typical 2's-complement system, to subtracting 16. – Igor Tandetnik Oct 31 '20 at 14:29
  • `while((x!=14))` seems odd. What if `x` is never exactly 14? What are you trying to achieve exactly? – cigien Oct 31 '20 at 14:30
  • Thank you for the clarification, I will read up more on this! @IgorTandetnik – RafflesiaBoy Oct 31 '20 at 14:32
  • Hi Cigien, I was just experimenting around with the code and was trying to figure out how nested loops worked haha, sorry if it caused any confusion to you instead @cigien – RafflesiaBoy Oct 31 '20 at 14:35
  • No need to apologize, experimenting is great way to learn :) In that case, I strongly suggest also learning how to use a debugger. Then you can step through the code line by line, to see exactly what the code does, and that will answer 99% of your questions :) – cigien Oct 31 '20 at 14:38
  • Ah ok, I will definitely look into that, it sounds like that will really help a lot, thanks again! @cigien – RafflesiaBoy Oct 31 '20 at 14:40
  • No problem :) I've closed this question as a duplicate. See that post, it's a good place to get started. Good luck :) – cigien Oct 31 '20 at 14:52

0 Answers0