-
If Statement
Whats wrong with my code?
Code:
#include <stdio.h>
main()
{
char x[10];
printf("Enter [True/False] : ");
scanf("%s", x);
if(x=="true")
printf("Great..\n");
else
printf("What's wrong?\n");
}
result:
Code:
root@invecta:~# gcc -o result if.c
root@invecta:~# ./result
Enter [True/False] : true
What's wrong?
root@invecta:~#
-
C does not know how to do this...
Look into the workings of strcmp()
-
In the context of your "if" statement, the string literal "true" is interpreted as an address where that string exists in memory. Also, "x" is interpreted as the address of the array on the stack. These two addresses are what's effectively being compared in your "if" test. Please see that these two addresses are NEVER going to be equal to each other and so such a test will always take the false branch. Now, if you were doing this in C++ and the variable "x" was a std::string, then your code would work as you think it should since the equality operator (==) is overloaded to compare such objects against a string literal. As mentioned, you need to use the strcmp function (in the string.h header) to compare the two strings and test the returned value from the function call - a 0 is returned if the two strings are equal.
-
It's not that simple with strings. Use this instead.
Code:
#include <string.h>
/* ... */
if (strcmp(x, "true") == 0)