Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize SDL_Color in C?

Tags:

c

sdl

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.

like image 530
Thomas Beaudet Avatar asked Jan 27 '26 06:01

Thomas Beaudet


2 Answers

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;
like image 133
blatinox Avatar answered Jan 28 '26 20:01

blatinox


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.

like image 39
Miguel Muñoz Avatar answered Jan 28 '26 20:01

Miguel Muñoz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!