简体   繁体   中英

Strange behaviour with getIntegerv() and std::cout

This code:

#include <iostream>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

int main(void)
{
    GLint version;
    glGetIntegerv(GL_MAJOR_VERSION, &version);
    std::cout << version << std::endl;
    //(Un)comment the next line
    //std::cout << "" << version << std::endl;
    glfwTerminate();
    return 0;
}

outputs:

32766

or

0
0

when the line is commented or uncommented, respectively.
I know that you have to init glfw and glew libraries before using some methods(with glfw initialized this still happening), but... How is possible that the previous line change its behavior commenting or uncommenting the next line? The machine goes to the past and execute the previous line? omg

PS: I know what is an "undefined behavior" but that doesn't mean that you can break the laws of physics, travel to the past and modify the behavior of some methods.

I know that you have to init glew libraries before using some methods, but... How is possible that the previous line change its behavior commenting or uncommenting the next line?

Because this is what the "undefined" in undefined behavior means.

When you call a GL function without a current GL context, anything can happen. So you have undefined behavior from the GL side here. However, in the real world, most implementations will just do nothing in that case, so version does not get written to, and you are printing the content of an uninitialized variable, so you have undefined behavior on the C++ side then. In the real world, you most likely print some contents of your stack, and by changing the code, you are changing the compiled result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM