Return type in C ++

#include<iostream>

int & fun();
int main()
{
    int p = fun();
    std::cout << p;
    return 0;
}

int & fun()
{
    int a=10;
    return a;
}

Why does this program not give an error in line No. 6 as "incorrect conversion from int * to int", as it happens if we do this?

 int x = 9;
 int a = &x;
+1
source share
6 answers

int&- a type; it means link to int.

&x- expression; it means take address x. The unary operator &is an address operator. He accepts the address of his argument. If it xis int, then the type &xis a "pointer to int" (that is int*).

int& int* - . ; , , , . -, , . , , ( * ->).

& . : , &, .


, fun , . , a , , . , . fun() p, , undefined.

, , , .

+5

№5 " int * int", , ?

, , . Undefined Behavior, , UB.

+1

, - :

int a = & x , a x -

int & p = fun() , p int-ok

+1

++ , , qrite int p = fun(), int p = &a; ( , , ). , , f. . BTW, , .

0

You do not return int *, you reconfigure int &. That is, you return a reference to an integer, not a pointer. This link may break up into int.

0
source

These are two different things, although they both use the ampersand symbol. In the first example, you return a reference to int, which is assigned to int. In the second example, you are trying to assign the address x (pointer) to int, which is illegal.

0
source

All Articles