Is hard coded value in function argument is a const refrence?

why following program fail to compile:

#include<iostream>
using namespace std;

int fun(int &x)
{
    return x;
}
int main()
{
    cout << fun(10);
    return 0;
}

It give following compilation error:
invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

To make it compile successfully , I have 2 options:
1. we have t use “const int fun(int &x)” instead of “int fun(int &x)”
2. use “int i=10;cout << fun(i);” instead of “cout << func (10)”

so, it seems like , if we pass a hard coded value to a function , it will be treated like “const reference”.

Am I right here? or there is any other reason that above program doesn’t compile?


Source: c++

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.