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

The while() loop is executing infinitely

I had a problem where have to print ASCII values of characters from 1 to 255 so I wrote this code:

#include<stdio.h>
int main()
{
     unsigned char a,z,A,Z;
     a=1;
    while (a<=255)
    {
        printf("the ascii value of %c is %d\n",a,a);
        a++;
    }
    return 0;
}

The code runs fine and prints the ASCII values till I think (a<=130) too but when I put the condition like while(a<=150) or while(a<=255)
it keeps executing infinitely. What may be the reason it is happening?

I was expecting that all the values will be printed.

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

>Solution :

Whether char is signed or unsigned on any given platform is implementation-defined. A signed char would overflow at a == 127, so a <= 150 can never become false.

a <= 255 can never become false regardless of the signedness of char. (Assuming 8-bit chars.)

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