A simple program about "char". What's wrong?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
User avatar
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

A simple program about "char". What's wrong?

Post by ImLazy » Sun Sep 25, 2005 11:08 am

Code: Select all

#include <iostream>
using namespace std;
int main(){
    char c;
    c=(char)128;
    if(c>'a'){
        cout<<">a"<<endl;
    }
    if(c==(char)128){
        cout<<"==128"<<endl;
    }
    if(c<(char)0){
        cout<<"<0"<<endl;
    }
    return 0;
}
I think the output should be

Code: Select all

>a
==128
but the actual output is

Code: Select all

==128
<0
Why???
(I run it in Dev-C++ and MinGW and VC++, they give the same output.)
I stay home. Don't call me out.

User avatar
little joey
Guru
Posts: 1080
Joined: Thu Dec 19, 2002 7:37 pm

Post by little joey » Sun Sep 25, 2005 12:00 pm

The type char is a 8 bit signed integer type, so 128 (binary 10000000) is actually treated as the value -1. I think you should use another integer type (unsigned char or int) to get what you want.

User avatar
ImLazy
Experienced poster
Posts: 215
Joined: Sat Jul 10, 2004 4:31 pm
Location: Shanghai, China

Post by ImLazy » Sun Sep 25, 2005 4:37 pm

Oh, thank you very much. I didn't even know there is unsigned char type before.
I stay home. Don't call me out.

Post Reply

Return to “C++”