Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this short program legal C++? [closed]

while solving a test on http://cppquiz.org I found this interesting piece of code :

#include <iostream>

int f(int& a, int& b) {
    a = 3;
    b = 4;
    return a + b;
}

int main () {
    int a = 1;
    int b = 2;
    int c = f(a, a);// note a,a
    std::cout << a << b << c;
}

My question is this program legal C++ or it isnt? Im concerned about strict aliasing.

like image 579
NoSenseEtAl Avatar asked Feb 17 '23 18:02

NoSenseEtAl


1 Answers

You mention strict aliasing – but strict aliasing is concerned with aliases of different types. It doesn’t apply here.

There’s no rule that forbids this code. It’s the moral equivalent of the following code:

int x = 42;
int& y = x;
int& z = x;

Or, more relevantly, it’s equivalent to having several child nodes refer to the same parent node in a tree data structure.

like image 195
Konrad Rudolph Avatar answered Feb 27 '23 21:02

Konrad Rudolph