Home > Backend Development > C++ > body text

How to Fix Comparison Error Between Pointer and Integer in C

Linda Hamilton
Release: 2024-10-23 16:10:02
Original
266 people have browsed it

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
Copy after login

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>
Copy after login

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>
    Copy after login
  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>
    Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!