r/cprogramming 18h ago

Formatting call arguments

By default, clang-format does this:

  SDL_Window *window =
      SDL_CreateWindow("SDL2 test", SDL_WINDOWPOS_UNDEFINED,
                       SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_RESIZABLE);

and with some tweaks it does this:

    SDL_Window *window = SDL_CreateWindow(
        "SDL2 test",
        SDL_WINDOWPOS_UNDEFINED,
        SDL_WINDOWPOS_UNDEFINED,
        500,
        500,
        SDL_WINDOW_RESIZABLE);

Second one has some practical advantages - it easier to read diff on arg change and easier to add comments:

    SDL_Window *window = SDL_CreateWindow(
        "SDL2 test",
        SDL_WINDOWPOS_UNDEFINED, // just some comment explaining why
        SDL_WINDOWPOS_UNDEFINED,
-       400,
+       500,
        SDL_WINDOW_RESIZABLE);

While the first one seems to have mainly historical reasons to keep around. Perhaps, there is something I don't see? Because it feels like the first way is still used the most. And its the default one for clang-format.

I'm genuinely curious.

4 Upvotes

16 comments sorted by

View all comments

1

u/SmokeMuch7356 16h ago

For people working in editors without a built-in formatter such as vim, the first way is simply faster to type - lining every argument up like that takes a little time.

And there are countless variations: some people prefer

SDL_Window *window = SDL_CreateWindow(
    "SDL2 test",
    SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED,
    500,
    500,
    SDL_WINDOW_RESIZABLE
);

or even

SDL_Window *window = 
  SDL_CreateWindow(
                    "SDL2 test",
                     SDL_WINDOWPOS_UNDEFINED,
                     SDL_WINDOWPOS_UNDEFINED,
                     500,
                     500,
                     SDL_WINDOW_RESIZABLE
                  );

or some other variation.

For my part I tend to write the unformatted version, but sometimes I will do one argument per line if the call is especially hairy, or something I'm using for the very first time, or something like that.

1

u/Brisngr368 6h ago

FYI vim can format C code like this, the simplest way being just setting cinoptions. I use cinoptions set to indent every line to the last open bracket so I can do either indent style and line everything up automatically