Creating a window outside the function where it will be used

Hi, I am just trying to increase my understanding. I can’t figure out why this doesn’t work:

bool Init(GLFWwindow* window)

    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    // Create a GLFWwindow object that we can use for GLFW's functions
    window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    return true;

// The MAIN function, from here we start the application and run the game loop
int main()

    GLFWwindow* window = nullptr;
    // Init GLFW
    return 0;

If I place
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, “LearnOpenGL”, nullptr, nullptr); into the main loop instead of inside Init() then there are no problems but why are these not the same?


You don’t state what your problem is. Your code as shown will simply exit after creating the window. Is that your problem?

If in your actual code you’re using you try to use the variable window in main() after Init then it will still be a nullptr, as whilst you would need to use GLFWwindow** pWindow and then set *pWindow = glfwCreateWindow(...) and call with Init(&window).

If that’s not your issue then please add what you’re getting and what you actually want to get.

Thanks Doug! You understood the problem! Your solution works. After some thinking I think it is because with the code that I first posted the pointer is passed by value so the address it points too cannot be modified, is that correct?

Not quite. You pass a pointer to the function, but since glfwCreateWindow returns a pointer you need to alter the value of the pointer, and not the value at the address the pointer points to!

So what you need is a pointer to a pointer GLFWwindow** pWindow and then you alter the value of what it points to *pWindow = glfwCreateWindow(...).

Alternatively your function could just return a pointer from your function, or NULL if it fails. That would make it a lot easier to reason about.