Curly brackets? how to place them?


I had a question about the use of curly brackets.
My teacher is telling me that I have to write the like this:

void test()
  //do something

But I wrote them my whole life like this:

void test() {
  // do something

Is it mandatory to do like the first example?


Not at all. It's purely a matter of preference. The Arduino style happens to be the second style ("1TBS").

Worth noting that, although the classic Arduino IDE's Auto Format tool allows the user freedom in the brace style they use (which usually ends up being a completely random mixture of the two), the new Arduino IDE 2.x's Auto format currently enforces the "1TBS" brace style, meaning that if you want to use the Auto Format tool you have no option in the matter.

So you might use that as support for your case to your teacher to allow you to use the "1TBS" style.

On the other hand, you might realize that annoying the person who is grading your work is not the wisest choice and comply with their formatting preference.

I think it actually may be a valuable lesson. When we're working on our own projects, we have freedom to do as we prefer. However, in professional, or even many hobby/volunteer open source projects, we have to effectively collaborate with others. If everyone stubbornly uses their own preference of formatting style, the code turns into an absolute mess. In this case, consistency trumps personal preference every time. You could waste a lot of time trying to convince the rest of the team to switch over to your preferred formatting style, or you can just go with the existing convention and get right to making things happen.

1 Like

The compiler doesn’t care.
Torvalds may care.

(I personally prefer your teacher’s edict, but ask him where s/he stands on K&R vs. Linux indentation)

Thanks for the quick replies!

Pert, I do agree with your second statement.

The first style, at least for function definitions, has some history behind it.
Because C function definitions USED to be written:

  int a;
  float b;
  char *c;
   /* Do Stuff */

Which would look really weird with any other brace placement.
This style is OBSOLETE, doesn’t type-check the parameters, and has other disadvantages. You should forget you ever saw it. And I shouldn’t have mentioned it!

we have to effectively collaborate with others.

Pert is 100% spot on with this observation. Consistency is much more important than personal preferences. In a (good) professional environment, there will be a “coding style guide” that specifies cosmetic details like this, along with “indent size”, “tabs vs spaces”, “always use braces even when they’re not required”, “camel case vs polish”, and more…


This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.