error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'const int')|

I was just learning macros and working of const pointers through a simple program of calculating area. Here's the code:

#include <iostream>
#define PI = 3.141592653589793238
#define AREA(r) (PI*new_r*new_r)
#define PERIMETER(r) (2*PI*new_r)
using namespace std;

int main()
{
    cout<<"Enter the radius:";
    const int r = 0;
    cin >> r;
    const int *new_r = &r;
    printf("\n%darea:"<<" "<<AREA(new_r)<<"\n%dPerimeter:"<< PERIMETER(new_r));
    return 0;
}

It is giving out this error;

C:\Users\aakash\Desktop\C++\Eight_C++\main.cpp|11|error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'const int')|

I'm a beginner so please explain if I'm lacking any basic/crucial knowledge here.

2 answers

  • answered 2020-06-27 04:11 Ghost

    const int r = 0;

    You are initializing a constant value, you can't reassign it as you've done

    cin >> r;

  • answered 2020-06-27 04:28 ganjaam

    There are couple of issues with the code.

    #define PI = 3.141592653589793238

    The proper format to declare macro is: #define <macroName> <macroValue>. There is no need to use = sign. And so the proper way should be #define PI 3.141592653589793238.

    #define AREA(r) (PI*new_r*new_r)
    #define PERIMETER(r) (2*PI*new_r)
    

    It is logical to use r in the formula instead of new_r. Also, new_r is a pointer and so it will not give the expected output.

    const int r = 0;
        cin >> r;
    

    This is the reason behind the error message! We use const during declaration of a variable to define that the assigned value of the variable should not be changed under any circumstances. By const int r = 0; we mean that the value of r should always be 0 and can not be changed. And that's why we can't input a value in r. So to store a value, we need to use another variable that is not const.

    printf("\n%darea:"<<" "<<AREA(new_r)<<"\n%dPerimeter:"<< PERIMETER(new_r));
    

    cout and printf() are two different things. printf() use format specifiers and not << to output values. Correct way to use printf() in this case:

    printf("\narea: %f\nPerimeter: %f", AREA((*new_r)), PERIMETER((*new_r)));
    

    So, the final code should look something like this -

    #include <iostream>
    #define PI 3.141592653589793238
    #define AREA(r) (PI*r*r)
    #define PERIMETER(r) (2*PI*r)
    
    using namespace std;
    
    int main()
    {
        cout<<"Enter the radius:";
        int r = 0;
        cin >> r;
        int *new_r = &r;
    
        printf("\narea: %f\nPerimeter: %f", AREA((*new_r)), PERIMETER((*new_r)));
        return 0;
    }