Comparison Error in C : Pointer vs. Integer
When attempting to compile a simple function from Bjarne Stroustrup's C book, third edition, developers may encounter the compile time error:
error: ISO C forbids comparison between pointer and integer
This issue arises when comparing a pointer with an integer. In the provided code:
#include
#include
using namespace std;
bool accept()
{
cout > answer;
if (answer == "y") return true;
return false;
}
The error appears in the if statement where answer is compared to a string literal ("y"). Since answer is a character variable, it must be compared to a character constant.
Solution
There are two solutions to this issue:
Use a string Variable:
Declare answer as a string type instead of char. This will allow you to compare answer to a string literal correctly:
string answer;
if (answer == "y") return true;
Use Character Constant:
Instead of comparing answer to a string literal, use a character constant enclosed in single quotes:
if (answer == 'y') return true; // Note single quotes for character constant
Both methods effectively resolve the error by ensuring that the comparison is between compatible types.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3