0
votes

I am currently learning how to use SDL 2. Using the Lazy Foo' SDL2 Tutorial, shown here, I have created a script that should show an image for 2 seconds before closing the program. Here is the script:

#include <SDL.h>
#include <stdio.h>

//Screen dimensions
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

SDL_Window* window = NULL;

SDL_Surface* screenSurface = NULL;

SDL_Surface* surfaceImage = NULL;

bool init();

bool loadMedia();

void close();

bool init()
{
    bool success = true;
    //initializes
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else{
    //creates the window
        window = SDL_CreateWindow("Testing!", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if( window = NULL )
        {
            printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            screenSurface = SDL_GetWindowSurface(window);
        }
    }

    return success;

}

bool loadMedia()
{
    bool success = true;
    surfaceImage = SDL_LoadBMP( "test.bmp" );
    if(surfaceImage = NULL)
    {
        printf(SDL_GetError());
        success = false;
    }

    return success;
}

void close()
{
    SDL_DestroyWindow(window);
    window = NULL;
    SDL_Quit();
}

int main( int argc, char* args[] )
{
    if(!init())
    {
        printf( "Failed to initialize!\n" );
    }
    else{
        SDL_FillRect(screenSurface, NULL, ( screenSurface->format, 0xFF, 0xFF, 0xFF ));
        if(!loadMedia())
        {
            printf(SDL_GetError());
        }
        else{

            SDL_BlitSurface(surfaceImage, NULL, screenSurface, NULL);
            SDL_UpdateWindowSurface(window);
        }

        SDL_Delay(2000);
        close();
        return 0;
    }
    return 0;
}

However, the Image is not showing. No errors appeared, the program ran like it should, except the image was not there. I have the bmp file in the same directory as the vcproj file. What is wrong with the code?

1

1 Answers

2
votes

Fix two lines of code:

Change if(window = NULL) to if(window == NULL)

and

if(surfaceImage = NULL) to if(surfaceImage == NULL).

This is a very common mistake--you almost always mean the second one, but the first one is valid, though it means something very different. A strategy to avoid making this same mistake in the future is to get in the habit of changing the order of the operands in the if:

if(NULL == window) works and is equivalent to if(window == NULL), but if(NULL = window) is a compiler error, so you will be tipped off to your mistake immediately if you make it.