Search code examples
c++strict-aliasing

Is this short program legal C++?


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.


Solution

  • 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.