The Difference Between Characters and Strings

Question: I am writing a program in C that asks for a one character answer from the user. The code I am writing is:

 char x;
printf("Enter answer:(y/n)\n");
scanf("%c",&x);
if (x == "y") {printf("you answered yes\n"); }

The compiler gives me an error about comparison between a variable and a pointer. Is there something I'm missing?
anonymous

Answer: The if statement should read:

 if (x == 'y') 

You need to specify a single character in single quotes. "y" is a character string of two characters - the 'y' followed by the null character that C and C++ always use to terminate strings. A character string such as "y" is accessed via a pointer to the start of the string rather than being accessed directly the way that a single character field would be and this is the cause of the error message that you are receiving.

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate