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:
<code class="cpp">#include <iostream> #include <string> using namespace std; bool accept() { cout << "Do you want to proceed (y or n)?\n"; char answer; cin >> answer; if (answer == "y") return true; return false; }</code>
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:
<code class="cpp">string answer; if (answer == "y") return true;</code>
Use Character Constant:
Instead of comparing answer to a string literal, use a character constant enclosed in single quotes:
<code class="cpp">if (answer == 'y') return true; // Note single quotes for character constant</code>
Both methods effectively resolve the error by ensuring that the comparison is between compatible types.
The above is the detailed content of How to Fix Comparison Error Between Pointer and Integer in C. For more information, please follow other related articles on the PHP Chinese website!