Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

This code didn't throw an exception or exit but runs infinitely why?

I was try an experiment and I expected this code to throw an exception or print ambiguous value for n and exit but its end up running infinitely. Why it runs infinitely?

#include <stdio.h>
 
int main() {

    int y=5;
    int n=4;

    while(y || n) {
        printf("n = %d y = %d\n",n,y);

        y--;
        n--;
    }

   return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The loop runs as along a y OR n are non-zero.

For the loop to terminate, y and n would both have to be zero at the top of the loop, but that never happens because y and n start off not being equal to each other and each of them goes down by one each iteration.

Also note that signed integer overflow/underflow is undefined behavior, so if you run the loop long enough for that to happen, there are no guarantees about what will happen.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading