Search code examples
c++vectorraytracing

Why is this return type valid?


I was having a look at the source code of this raytracer. On the file named algebra3.cpp at line 145 we can see this function:

inline vec2 operator * (const mat3& a, const vec2& v) {
    vec3 av;

    av.n[VX] = a.v[0].n[VX]*v.n[VX] + a.v[0].n[VY]*v.n[VY] + a.v[0].n[VZ];
    av.n[VY] = a.v[1].n[VX]*v.n[VX] + a.v[1].n[VY]*v.n[VY] + a.v[1].n[VZ];
    av.n[VZ] = a.v[2].n[VX]*v.n[VX] + a.v[2].n[VY]*v.n[VY] + a.v[2].n[VZ];
    return av;
}

It should return a vec2 object instead its returning a vec3. Why is that?


Solution

  • If vec3 is implicitly convertible to vec2, then the function correct as far as the compiler knows.

    It would seem silly to throw away av.n[VZ] right after calculating it. If that's what the program does, then I'm going to guess that it could be a programmer mistake.

    Without more information about what the function is supposed to do, it's impossible to tell whether it should actually return a vec3, or whether the extra calculation is simply dead code left over and the temporary should be of type vec2. Or whether the current code is exactly what the programmer intended.