Code Style

One-line if/for/while/do

I recommend to always put curly brackets (begin/end) in the structural operators like conditions and loops. I.e. instead of

if ( a < 0 ) cout << "a is negative" << endl;
for ( int i=0; i<N; i++ ) cout << i << ' ';

write

if ( a < 0 ) {
    cout << "a is negative" << endl;
}
for ( int i=0; i<N; i++ ) {
    cout << i << ' ';
}

Why?

First, it makes your code clearer. In this way, you explicitly define the scope, the block of code to be executed when the respective condition is true and control flow enters the operator.

Second, often there will come a moment when you would like to add a debug print, to perform an additional operation or to split the single complex line you have into several ones to make it easy to understand. At this time, there is a very high risk that you’ll forget to enclose them in a block by adding the curly brackets. In this case, if you don’t test your program thoroughly, you’ll miss that change on the spot. Later – even a half an hour later – it may become incredibly difficult to trace back, to find the part of code with the mistake and to see such mistake. Because everything seems to be fine, especially if there is a lot of operators without curly brackets spread through the code.

Advertisements
Standard

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s