Skip to content

Placing braces

Alexandre Gautier edited this page Oct 12, 2016 · 1 revision

The other issue that always comes up in C styling is the placement of braces.
Unlike the indent size, there are few technical reasons to choose one placement strategy over the other, but the preferred way, is to put both the opening and the closing braces first, thusly:

	if (x == 1)
	{
		some_code = here;
	}

This applies to almost all non-function statement blocks: if, switch, for, while.
E.g.:

	switch (action)
	{
	case CASE_ADD:
		return ("add");
	case CASE_REMOVE:
		return ("remove");
	case CASE_CHANGE:
		return ("change");
	default:
		return (NULL);
	}

and

	if (x == y)
	{
		...
	}
	else if (x > y)
	{
		...
	}
	else
	{
		....
	}

This applies to functions too: they have the opening brace at the beginning of the next line, thus:

	int function(int x)
	{
		body of function
	}

Exceptions

Note that the closing brace is empty on a line of its own, except in the cases where it is followed by a continuation of the same statement, ie a while in a do-statement, like this:

	do {
		body of do-loop
	} while (condition);

Do not unnecessarily use braces where a single statement will do.

	if (condition)
		action();

and

	if (condition)
		do_this();
	else
		do_that();

This does not apply if only one branch of a conditional statement is a single statement; in the latter case use braces in both branches:

	if (condition)
	{
		do_this();
		do_that();
	}
	else
	{
		otherwise();
	}

0. Betty cli

0.1 - Betty-style usage

0.2 - Betty-doc usage

0.3 - References

1. Coding style

1.1 - Indentation

1.2 - Breaking long lines and strings

1.3 - Placing Braces

1.4 - Placing Spaces

1.5 - Naming

1.6 - Functions

1.7 - Commenting

1.8 - Macros and Enums

1.9 - Header files

2. Documentation

2.1 - Functions

2.2 - Data structures

3. Tools

3.1 - Emacs

3.2 - Vim

3.3 - Atom

Clone this wiki locally