0

why this code shows error while compiling?

#include <iostream>

using namespace std;

void foo(int& x){
   // cout<<x;
}

int main(){
    //int x=3;
    foo(3);
    return 0;
}

but by changing the argument to const it compiles properly

#include <iostream>

using namespace std;

void foo(const int& x){
   // cout<<x;
}

int main(){
    //int x=3;
    foo(3);
    return 0;
}

but i am still passing an integer so how does it compiles by adding const in the argument?

  • The usual purpose of using a reference parameter is so you can modify the caller's variable by assigning to the parameter. What should be modified when you have a reference to `3` instead of a variable? – Barmar Jun 23 '16 at 22:43

1 Answers1

2

int& x can be changed, so it can't get reference to const int like 3.

const int& x can't be changed and type is perfectly match to const int like 3, so why you expect it to fail?

SHR
  • 7,940
  • 9
  • 38
  • 57