C++ tutorial: layout
Lay out the program for the benefit of the reader
On the whole the C++ compiler does not care about how the program is layed out.
You should arrange your statements in such a way as to make things clear for a
human reader, not for the computer. For example, in the program
welcome2.cpp the function 'FirstLine' is defined
as follows:
/*============================================
FirstLine
displays the first line of the message
============================================*/
void FirstLine (void)
{
cout << "Welcome to BIS4221:\n";
}
Note the following about the layout of this function.
- The function starts with a comment, explaining what it does.
- The statements comprising the function are indented (spaced in from the edge) to
indicate graphically that these statements 'belong to' the function FirstLine
- The opening and closing braces are on separate lines
There are various layout styles in use
I normally use the layout shown above for functions, but there are other methods. Some people,
for example, don't indent the braces, giving this layout:
void FirstLine (void)
{
cout << "Welcome to BIS4221:\n";
}
Other people prefer to put the opening brace on the same line as the function, like
this:
void FirstLine (void){
cout << "Welcome to BIS4221:\n";
}
Personally, I prefer my way of doing it, but it's all a matter of taste. The three
schemes shown above are all identical to the computer and equally acceptable. What is
not acceptable, however, is to use inconsistent layout styles or, worse, no
layout at all. For example, I could have arranged the function FirstLine like this:
void
FirstLine (
void) {cout
<< "Welcome to BIS4221:\n";
}
and the program would still work. I hope you will agree that this is much more
difficult for a human reader to follow.
Start as you mean to go on
From the very first programs you write, even if they are only a few lines long,
you should get into the habit of adopting a consistent layout.
|