Unable to initialise SDL_Vertex

Hello

I am getting 3 errors:

>> vert[0].color = {255, 0, 0, 255}; >> error, expected expression before ‘{’
>> vert[1].color = {0, 0, 255, 255}; >> error, expected expression before ‘{’
>> vert[2].color = {0, 255, 0, 255}; >> error, expected expression before ‘{’

when compiling the code below with gcc that I copy/pasted from here: SDL_RenderGeometry - SDL Wiki

It is to be noted that I don’t get any error when using SDL_Color test = {255,0,0,255};

#include <SDL.h>

int main(int argc, char *argv[]) 
{
  SDL_bool quit = SDL_FALSE;
  SDL_Window *window = SDL_CreateWindow("Triangle Example", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

  SDL_Vertex vert[3];

  // center
  vert[0].position.x = 400;
  vert[0].position.y = 150;
  vert[0].color = {255, 0, 0, 255};

  // left
  vert[1].position.x = 200;
  vert[1].position.y = 450;
  vert[1].color = {0, 0, 255, 255};

  // right 
  vert[2].position.x = 600;
  vert[2].position.y = 450;
  vert[2].color = {0, 255, 0, 255};
 
  while (!quit) {
   SDL_Event ev;
   while (SDL_PollEvent(&ev) != 0) {
      switch(ev.type) {
        case SDL_QUIT: 
        quit = SDL_TRUE;
        break;
      }
    }
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);

    SDL_RenderGeometry(renderer, NULL, vert, 3, NULL, 0);

    SDL_RenderPresent(renderer);
  }
  
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();
  return 0;
}

I came across this stack overflow post, which basically explains that in C only initialization can be done with the curly brackets style, not assignment. That explains why SDL_Color test = {255,0,0,255}; works. In the same post, someone suggests the following if using C99:

verts[0].color = (struct SDL_Color){255, 0, 0, 255};

Assigning each value separately like it’s being done with position is also an option.

Compiling in C++ would also give no errors, but maybe the wiki example should be updated?

Thank you so much it’s working now!

It might be worth updating the wiki.

Yes, the wiki should be updated. Can you try if verts[0].color = (SDL_Color){255, 0, 0, 255}; (without the struct) also works?
I think it should because there’s a typedef that allows using SDL_Color without struct in C in general, but I’m not 100% sure about this specific case.

I can make the according edit once I know if struct is necessary or not

Yes verts[0].color = (SDL_Color){255, 0, 0, 255}; compiles without error.

1 Like

Thanks; I already fixed the wiki article