How does c compare character variable against string?
The following code is completely ok in C but not in C++. In following code if
statement is always false. How C compares character variable against string?
int main()
{
char ch='a';
if(ch=="a")
printf("confusion");
return 0;
}
Solution 1:
The following code is completely ok in C
No, Not at all.
In your code
if(ch=="a")
is essentially trying to compare the value of ch
with the base address of the string literal "a"
,. This is meaning-and-use-less.
What you want here, is to use single quotes ('
) to denote a char
literal, like
if(ch == 'a')
NOTE 1:
To elaborate on the difference between single quotes for char
literals and double quotes for string literal s,
For char
literal, C11
, chapter §6.4.4.4
An integer character constant is a sequence of one or more multibyte characters enclosed in single-quotes, as in
'x'
and, for string literal, chapter §6.4.5
Acharacter string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in
"xyz"
.
NOTE 2:
That said, as a note, the recommend signature of main()
is int main(void)
.
Solution 2:
I wouldn't say the code is okay in either language.
'a'
is a single character. It is actually a small integer, having as its value the value of the given character in the machine's character set (almost invariably ASCII). So 'a'
has the value 97, as you can see by running
char c = 'a';
printf("%d\n", c);
"a"
, on the other hand, is a string. It is an array of characters, terminated by a null character. In C, arrays are almost always referred to by pointers to their first element, so in this case the string constant "a"
acts like a pointer to an array of two characters, 'a'
and the terminating '\0'
. You could see that by running
char *str = "a";
printf("%d %d\n", str[0], str[1]);
This will print
97 0
Now, we don't know where in memory the compiler will choose to put our string, so we don't know what the value of the pointer will be, but it's safe to say that it will never be equal to 97. So the comparison if(ch=="a")
will always be false.
When you need to compare a character and a string, you have two choices. You can compare the character to the first character of the string:
if(c == str[0])
printf("they are equal\n");
else printf("confusion\n");
Or you can construct a string from the character, and compare that. In C, that might look like this:
char tmpstr[2];
tmpstr[0] = c;
tmpstr[1] = '\0';
if(strcmp(tmpstr, str) == 0)
printf("they are equal\n");
else printf("confusion\n");
That's the answer for C. There's a different, more powerful string type in C++, so things would be different in that language.
Solution 3:
There is difference between 'a'
(a character) and "a"
(a string having two characters a
and \0
). ch=="a"
comparison will be evaluated to false
because in this expression "a"
will converted to pointer to its first element and of course that address is not a character but a hexadecimal number.
Change it to
if(ch=='a')