views:

180

answers:

6

I have this snippet of the code

char    *str = “123”;
if(str[0] == 1) printf("Hello\n");

why I can't receive my Hello thanks in advance! how exactly compiler does this comparison if(str[0] == 1)?

+13  A: 

You want to do this:

if (str[0] == '1') ...

The difference is that you are comparing str[0] to the number 1, while my code above is comparing str[0] to the character '1' (which has ASCII value 49). Not all programming languages treat characters and numbers interchangeably in this way, but C does.

Check out ASCII for more information about how computers map numbers to characters.

Greg Hewgill
+1  A: 

you're comparing a char to an int, it should be

if(str[0] == '1')
Bwmat
+7  A: 

First the right way is to do this:

if(str[0] == '1')

Or :

if(str[0] == 49)


Second, you must take care of the difference between 1 and '1'

  • 1 is a integer value...
  • '1' is a character whose ASCII equals 49

Which means: ('1'==1) is false !!

However ('1'==49) is true !!

When you write '1' in C/C++ it -automatically- be translated to the corresponding ASCII 49, that is how '1' is actually represented in C/C++

Betamoo
how exactly compiler does this comparison?
lego69
Please take a look on the edit
Betamoo
Why -1 ...... ?
Betamoo
A: 

you need to ask

*str = “123”; if(str[0] == '1'') printf("Hello\n");

See those single quotes around 1? You ned to compare a character and you are comparing an integer.

Mawg
A: 

Try using if(str[0] == '1') instead of comparing with 1 what means one and true in C :)

veritas
+2  A: 

This is because you are comparing the first character of str to the number 1. The actual character code of '1' is 49. So, either of these will work:

if (str[0] == '1')

if (str[0] == 49)

Remember that 1 isn't the same as '1'. The first one is a number, the second one is a character. If you want to learn more about this, you should probably look here: http://en.wikipedia.org/wiki/Character_encoding

Adrian