Home >Backend Development >C++ >Why Does ISO C Forbid Comparing Pointers and Integers, and How Can I Fix This Error in My Code?
ISO C Comparison Error: Pointers and Integers
While working on an example from Bjarne Stroustrup's C book, some users have encountered a compile-time error indicating that ISO C forbids comparison between a pointer and an integer. This issue arises from a comparison involving a char variable and a string constant in the accept() function.
Cause:
The error occurs because ISO C prohibits direct comparison of a character pointer (such as char*) with an integer (such as the numerical value of a character enclosed in double quotes, e.g., "y").
Solutions:
There are two primary ways to resolve this error:
Preferable Approach: Using a String Variable:
<code class="cpp">#include <iostream> #include <string> using namespace std; bool accept() { cout << "Do you want to proceed (y or n)?\n"; string answer; cin >> answer; if (answer == "y") return true; return false; }</code>
Alternative Approach: Using Single Quotes:
<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 above is the detailed content of Why Does ISO C Forbid Comparing Pointers and Integers, and How Can I Fix This Error in My Code?. For more information, please follow other related articles on the PHP Chinese website!