Sunday 20 November 2011

What is the correct way to use braces? in C programming

What is the correct way to use braces?

In C, there is no right and wrong way to use braces—as long as you have a closing brace for every opening brace, you will not have brace problems in your programs. However, three prominent bracing styles are commonly used: Kernighan and Ritchie, Allman, and Whitesmiths. These three styles will be discussed next.
 
In the book The C Programming Language, Brian Kernighan and Dennis Ritchie introduced their style of implementing braces. The style looks like this:

if (argc < 3) {
printf(“Error! Not enough arguments. Correct usage is:\n”);
printf(“C:>copyfile <source_file> <destination_file>\n”);
exit(1);
}
else {
open_files();
while (!feof(infile)) {
read_data();
write_data();
}
close_files();
}

Notice that with the K&R style, the opening brace is placed on the same line as the statement it is used with,
and the closing brace is aligned below the statement it closes. For instance, in the preceding example, the if
statement has its opening brace on the same line, and its closing brace is aligned below it. The same is true
of the if statement’s corresponding else condition and of the while statement that occurs later in the
program.

Here is the same example, except this time the Allman brace style is used:

if (argc < 3)
{
printf(“Error! Not enough arguments. Correct usage is:\n”);
printf(“C:>copyfile <source_file> <destination_file>\n”);
exit(1);
}
else
{
open_files();
while (!feof(infile))
{
read_data();
write_data();
}
close_files();
}

Notice that with the Allman style, each brace is placed on its own line. Both the opening and the closing braces are aligned with the statement that is used.
Here is the same example with the Whitesmiths style of bracing:
if (argc < 3)
{
printf(“Error! Not enough arguments. Correct usage is:\n”);
printf(“C:>copyfile <source_file> <destination_file>\n”);
exit(1);
}
else
{
open_files();
while (!feof(infile))
{
read_data();
write_data();
}
close_files();
}

As with the Allman style, the Whitesmiths style calls for putting braces on their own lines. However, the braces are indented to be aligned with the statements the braces contain. For instance, in the preceding example, the opening brace of the if statement is aligned with the first printf() function call. Whatever method you choose to use, be consistent—and you will help yourself and others read your programs more easily.

Cross Reference:

XIX.5: What is camel notation?
XIX.7: What is the correct way to name a function?
XIX.10: What is Hungarian notation, and should I use it?

No comments:

Post a Comment