Thomas Beaudet
Thomas Beaudet

Reputation: 89

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.

Upvotes: 3

Views: 10680

Answers (3)

blkkatana
blkkatana

Reputation: 1

I think this is what you're looking for:

SDL_Color color;
color = (SDL_Color){255, 255, 255};

Upvotes: 0

blatinox
blatinox

Reputation: 843

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;

Upvotes: 5

Miguel Muñoz
Miguel Muñoz

Reputation: 326

I think you can use the expression in braces only at the initialization of the variable, not in an assignment:

Initialization:

SDL_Color color = { 255, 255, 255 };  // By the way, maybe set also color.a

Assignment (member by member):

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

See more information about struct initialization in How to initialize a struct in accordance with C programming language standards.

Upvotes: 3

Related Questions