Is undefined behavior for a variable without initialization by reference?

I have the following code:

#include <iostream>

void f(int &x) {
    x = 5;
}

int main() {
    int x;
    f(x);
    std::cout << x << std::endl;
    return 0;
}

Does this code cause undefined behavior in C ++? g ++ compiles it without any warnings, and the code outputs 5(as expected?).

+4
source share
3 answers

There is no undefined behavior in this code. It would be undefined to use an uninitialized variable before it is assigned a value, but it is well defined to pass the link and to complete the job through the link.

+10
source

Undefined , (. ยง 8.5/12 ++ 14).

x , x, . x . ( : a int const double&, , double.)

+5

, undefined, - 5. void f(int& x), int& , , .

, undefined :

int& f() {
    int x = 5;
    return x; //return a reference of a variable that will not exist
    //after f finished
} 

int main() {
    std::cout << f() << std::endl; //undefined behavior 
}

This behavior is undefined, since links do not take responsibility for maintaining the distributed data to which they refer, the link simply changes and reads the values โ€‹โ€‹if they are valid. Therefore, after completion, the f()link will point to invalid memory.

+2
source

Source: https://habr.com/ru/post/1628056/


All Articles