I'm trying to improve the readability and overall organization of my project(s) which use SDL2. I'm trying to understand what I'm doing wrong when it comes to initializing members of a nested struct when it comes to SDL_Rect.
This is what I'm trying to achieve:
struct gfx {
SDL_Rect rect;
} gfx;
void example()
{
gfx.rect = {0,0,1280,720};
return;
}
However, this produces an "Expression Expected" error.
So, what I have been doing, which does work, but just creates a ton of clutter, is this:
struct gfx {
SDL_Rect rect;
} gfx;
void example()
{
gfx.rect.x = 0;
gfx.rect.y = 0;
gfx.rect.w = 1280;
gfx.rect.h = 720;
return;
}
Is it possible to achieve a shorthand version as shown, or is this just the way it needs to be?
Here is a link to the definition of the SDL_Rect struct: https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlrect.html
I'm using xCode 12.5.1, writing the project in C, with Clang, C99.
CodePudding user response:
This seems to work:
gfx x = {.rect = {.x = 0, .y = 0, .w = 1280, .h = 720}};
This seems to work too, but it may result in extra copy
SDL_Rect r = {.x = 0, .y = 0, .w = 1280, .h = 720};
gfx y = {.rect = r};
most examples here initialize struct members by names.
CodePudding user response:
You can use the compound literal syntax to achieve something similar:
gfx.rect = (SDL_Rect){0,0,1280,720};
This has a little overhead of creating an extra local object of type SDL_Rect
and copying it into gfx.rect
.
For reference: C11 Standard draft, 6.5.2.5 Compound Literals