Search code examples
csdl

How to initialize SDL_Color in C?


I am making a Graphical Client in C with SDL library and I have a problem when I want to set my SDL_Color type.

I declare my variable as

SDL_Color color;
color = {255, 255, 255};
/* rest of code */

then gcc tells me:

25:11: error: expected expression before ‘{’ token color = {0, 0, 0};

I found pretty good answers on C++ cases with some operator overloading but I'm afraid I really don't know how to fix this one in C.


Solution

  • You can not assign a value to a structure like this. You can only do this to initialize your structure :

    SDL_Color color = {255, 255, 255};
    

    You can also use a designated initializer:

    SDL_Color color = {.r = 255, .g = 255, .b = 255};
    

    See the 3 ways to initialize a structure.

    If you want to change the value of your structure after its declaration, you have to change values member by member:

    SDL_Color color;
    color.r = 255;
    color.g = 255;
    color.b = 255;