Beginning programmer here…
I’m writing a very simply program for my computer science class and I ran into an issue that I’d like to know more about. Here is my code:
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
char courseLevel;
cout << "Will you be taking graduate or undergraduate level courses (enter 'U'"
" for undergraduate,'G' for graduate.";
cin >> courseLevel;
if (courseLevel == "U")
{
cout << "You selected undergraduate level courses.";
}
return 0;
}
I’m getting two error messages for my if statement:
1) Result of comparison against a string literal is unspecified (use strncmp instead).
2) Comparison between pointer and integer (‘int’ and ‘const char*’).
I seem to have resolved the issue by enclosing my U in single quotes, or the program at least works anyway. But, as I stated, I’d simply like to understand why I was getting the error so I can get a better understanding of what I’m doing.
You need to use single quotes instead.
In C, (and many other languages) a character constant is a single character1 contained in single quotes:
While a string literal is any number of characters contained in double quotes:
You declared
courseLevelas a single character:char courseLevel;So you can only compare that to another singlechar.When you do
if (courseLevel == "U"), the left side is achar, while the right side is aconst char*— a pointer to the firstcharin that string literal. Your compiler is telling you this:So your options are:
Or, for sake of example:
Note for completeness: You can have mulit-character constants:
int a = ‘abcd’; // 0x61626364 in GCC
But this is certainly not what you’re looking for.