Home > Backend Development > C++ > Why Does C Forbid Comparing Pointers and Integers?

Why Does C Forbid Comparing Pointers and Integers?

Linda Hamilton
Release: 2024-10-28 08:15:02
Original
907 people have browsed it

Why Does C   Forbid Comparing Pointers and Integers?

Compiler Error: ISO C 's Prohibition of Pointer-Integer Comparisons

While experimenting with a simple function from Bjarne Stroustrup's C textbook, developers frequently encounter the compile error: "ISO C forbids comparison between pointer and integer." This error stems from the comparison between a pointer and an integer.

One instance of this issue arises when comparing a character input to the string "y". 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 occurs because the code defines answer as a character (char), while "y" is a string literal. To resolve this, you have two options:

  1. Convert the string literal to a character: Use answer == 'y' to compare the character input to the character 'y'.
  2. Use a string instead of a character: Declare answer as a string (string answer;) and then compare it to the string "y".

Both solutions address the compiler's restriction by ensuring that you are comparing a pointer to an integer with a pointer to another integer or a pointer to a string.

The above is the detailed content of Why Does C Forbid Comparing Pointers and Integers?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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