Search code examples
c++implicit-conversionreturn-typefunction-definitionincompatibletypeerror

Returning an array in c++ conversion function


I am trying to learn c++ with OpenGL. OpenGL renders on a coordinate system from -1 to 1 on the x and y axis. I am trying to make a function to convert pixels to openGL coordinates. I have this code:

float pixelsToCoordinates(int pixels[2]) {
    float r[2] = { (pixels[0] - windowWidth / 2) / (windowWidth / 2) * windowWidth / windowHeight, (pixels[1] - windowHeight / 2) / (windowHeight / 2) };
    return r;
}

I get this error on cpp return r;:

Severity Code Description Project File Line Suppression State Error (active) E0120 return value type does not match the function type OpenGL-Engine

I think it has something to do with how arrays work in c++. What is th issue here? Thanks in advance.


Solution

  • Th expression in the return type

    return r;
    

    has the type float * due to the implicit conversion of an array designator to a pointer to its first element.

    On the other hand. the return type of the function is float.

    So the compiler issues an error message because there is no implicit conversion from the pointer type float * to the type float.

    But if you will, change the return type of the function from float to float * there will be another problem of returning a pointer to a local array that will not be alive after exiting the function

    As your array contains only two elements then you could return an object of the type std::pair<float, float> instead of trying to return an array.

    For example

    #include <utility>
    
    //...
    
    std::pair<float, float> pixelsToCoordinates( const int pixels[] ) {
        return { (pixels[0] - windowWidth / 2.0f) / (windowWidth / 2.0f) * windowWidth / windowHeight, (pixels[1] - windowHeight / 2.0f) / (windowHeight / 2.0f) };
    }
    

    Another alternative is to return an object of the type std::array<float, 2>.

    #include <array>
    
    //...
    
    std::array<float, 2> pixelsToCoordinates( const int pixels[] ) {
        return { (pixels[0] - windowWidth / 2.0f) / (windowWidth / 2.0f) * windowWidth / windowHeight, (pixels[1] - windowHeight / 2.0f) / (windowHeight / 2.0f) };
    }
    

    And one more alternative is to define the destination array in the caller of the function and pass it as an argument to the function. For example

    float ( & pixelsToCoordinates( const int pixels[], float ( &a )[2] ) )[2];
    

    Pay attention to that if you want to get values of the type float then in general you should use expressions of the type float used as initializers.