Search code examples
c++c++11opengltype-conversionnarrowing

C++ / OpenGL: Texture to pixmap example - narrowing conversion error


I am trying to run this texture to pixmap example from OpenGL and get the following error

tex_to_pix.cpp:40:1: error: narrowing conversion of ‘4294967295u’ from ‘unsigned int’ to ‘int’ inside { } [-Wnarrowing]

The error refers to the following code block of the example:

const int pixmap_config[] = {
    GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
    GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
    GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
    GLX_DOUBLEBUFFER, False,
    GLX_Y_INVERTED_EXT, GLX_DONT_CARE,
    None
};

What is the reason for this error?

Is it a compiler or c++11 problem?

Is there a way i can either make my compiler ignore -Wnarrowing or make a safe conversion?


Solution

  • The issue is with GLX_DONT_CARE which is defined as:

    #define GLX_DONT_CARE                     0xFFFFFFFF
    

    Because this value does not fit into a 32-bit int, its type is unsigned int (see this answer). The rules for narrowing conversion were indeed changed in c++11.

    Trying to implicitly convert this unsigned int into an int causes the narrowing conversion warning. As shown in this answer, the narrowing problem can be fixed by using static_cast(GLX_DONT_CARE & 0xFFFFFFFF) instead of GLX_DONT_CARE

    const int pixmap_config[] = {
        GLX_BIND_TO_TEXTURE_RGBA_EXT, True,
        GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
        GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
        GLX_DOUBLEBUFFER, False,
        GLX_Y_INVERTED_EXT, static_cast<int>(GLX_DONT_CARE & 0xFFFFFFFF),
        None
    };
    

    Alternatively, disable narrowing conversion errors in your compiler (unspecified).