"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Fix Comparison Error Between Pointer and Integer in C++

How to Fix Comparison Error Between Pointer and Integer in C++

Published on 2024-11-18
Browse:294

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:

#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:

  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:

    string answer;
    if (answer == "y") return true;
  2. 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.

Release Statement This article is reprinted at: 1729663819 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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