Home  >  Article  >  Backend Development  >  How to Fix Comparison Error Between Pointer and Integer in C

How to Fix Comparison Error Between Pointer and Integer in C

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 16:10:02267browse

How to Fix Comparison Error Between Pointer and Integer in C

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:

  1. 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>
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn