Home > Backend Development > C++ > Why Does ISO C Forbid Comparing Pointers and Integers, and How Can I Fix This Error in My Code?

Why Does ISO C Forbid Comparing Pointers and Integers, and How Can I Fix This Error in My Code?

Barbara Streisand
Release: 2024-10-29 14:05:29
Original
677 people have browsed it

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:

  1. Preferable Approach: Using a String Variable:

    • Change the type of answer to string. This allows direct comparison with the string constant "y," resolving the issue.
    <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>
    Copy after login
  2. Alternative Approach: Using Single Quotes:

    • If using a char variable is essential, enclose the character constant in single quotes to represent a char constant.
    <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 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!

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