Home > Net >  Why when my char variable reaches the [del] character (127) value my C program enters into an infi
Why when my char variable reaches the [del] character (127) value my C program enters into an infi

Time:01-12

Here's my code:

#include <iostream>
int main()
{
    char x = 32;
    while (x <= 126) {
        std::cout << x << "\n";
        x  = 1;
    }
}

Until here, all goes right, but if I change my code to:

#include <iostream>
int main()
{
    char x = 32;
    while (x <= 127/*here the "bad" change*/) {
        std::cout << x << "\n";
        x  = 1;
    }
}

to try to print the [del] character, my program goes into an infinite loop and starts print a lot of other characters which I don't want. Why?

CodePudding user response:

Turn on your warning options!! (-Wextra for GCC)

test.cpp: In function 'int main()':
test.cpp:41:15: warning: comparison is always true due to limited range of data type [-Wtype-limits]
   41 |     while ( x <= 127 )
      |             ~~^~~~~~

I guess the warning message is pretty self-explanatory.

CodePudding user response:

Every value that fits into an 8-bit signed variable is less than or equal to 127. So if your platform uses 8-bit signed variables to hold characters, your loop will never exit.

CodePudding user response:

When x reach 127 it's flipped to -128 in the next round [-128 to 127]

enter image description here

CodePudding user response:

Thank you to all, I've replaced the char variable's type with an unsigned one and now the program works fine, here's my new code:

#include <iostream>
int main()
{
    unsigned char x = 0;
    while (x < 255) {
        x  = 1;
        std::cout << short int(x) << ":\t" << x << "\n";
    }
}

CodePudding user response:

American Standard Code for Information Interchange. ASCII Character Set. A char variable in C is a one-byte memory location where a single character value can be stored. Because one byte can hold values between 0 and 255 that means there are up to 256 different characters in the ASCII character set.

Now For your solution, you can try below code up to 127 or complete 256

Very Simple : For printing ASCII values of all characters in C , use a for loop to execute a block of code 255 times. That is, the loop variable I start with 0 and ends with 255.

#include<iostream>
using namespace std;
int main()
{
char ch;
int i;
cout<<"Character\t\tASCII Value\n";
for(i=0; i<255; i  )
{
    ch = i;
    cout<<ch<<" | "<<i<<endl;
}
cout<<endl;
return 0;
}
  •  Tags:  
  • Related