Monday, 20 February 2012

Problem With One-line if Statement in C++

The simplest if statement in C++ is one line in this form:

if (condition) statement;

But it’s possible to include multiple statements as in:

if (condition) statement[, statement...];

Either use should be contrasted to ones using a block statement.

Note the use of a comma to separate each statement and not a semicolon. To understand what can go wrong, look at the sample code.

Sample Code:

The sample code was created in MS Visual C++ as a Windows Form Application. It contains a form (Form1) that displays when the program runs. The sample code, contained in the Form Load Event, executes and adds text to a RichTextBox named rtOut.

// Declare variables.
int a, b;

// One statement after if leads to an expected result.
if (true) a=10;
rtOut->Text += "a is " + a + ".\n";

// Two statements after if with a comma leads to an expected result.
if (true) a=10, b=20;
rtOut->Text += "a is " + a + " and b is " + b + ".\n";

// Two statements after if using semicolon may be a problem.
// First change a's value.
a = 100;
if (false) a=10; b=200;
rtOut->Text += "a is " + a + " and b is " + b + ".\n";


a is 10.
a is 10 and b is 20.
a is 100 and b is 200.

The first if statement executed as expected and assigned the value of 10 to variable a.

The second if statement again executed the two statements and changed the values of a and b as expected, but the third use of if creates a surprise.

We changed the value of a to 100 and it remained at 100. The assignment statement of a=10 isn’t executed. A quick look at the statement leads you to believe the assignment of 200 to b is part of the if statement and shouldn’t get executed because the condition isn’t true, but the assignment of 200 to b is executed because the if statement ends with the semicolon. The ‘b=200;’ statement is really a new line of C++ code unaffected by the if statement.

This line of code:

if (false) a=10; b=200;

is the same as this:

if (false) a=10;

For certainty and readability, it’s better to write the code with a block statement.

No comments:

Post a Comment