Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operand types are incompatible ("char" and "const char*")

Tags:

c++

arrays

c

types

I'm receiving the following error...

Operand types are incompatible ("char" and "const char*")

... when trying to perform an if statement. I'm assuming I'm not understanding how the input value is stored although I'm unsure if I can just cast it into the matching type?

Example code to reproduce is:

char userInput_Text[3];

if (userInput_Text[1] == "y") {
    // Do stuff.
}

I'm not sure what's causing this. It would appear that one type is a char and the other is a const char pointer although I'm unsure of what, for reference this error also occurs when I'm not using an array).

And tips / feedback would be much appreciated.

like image 251
LeviTheDegu Avatar asked Jan 27 '13 03:01

LeviTheDegu


1 Answers

Double quotes are the shortcut syntax for a c-string in C++. If you want to compare a single character, you must use single quotes instead. You can simply change your code to this:

char userInput_Text[3];

if (userInput_Text[1] == 'y') { // <-- Single quotes here.
    // Do stuff.
}

For reference:

  • "x" = const char *
  • 'x' = char
like image 160
Karl Nicoll Avatar answered Oct 13 '22 10:10

Karl Nicoll