# can someone explain if statements in c++

• 02-23-2013
c++noob145
can someone explain if statements in c++
Am I suppose to use curly braces in if statements

In my textbook it shows if statements without curly braces

like this
Code:

```if(x=0) cout<< x << "is 0" <<endl;```
or is it suppose to be like this

Code:

```if(x=0){ cout<< x << "is 0" <<endl; }```

or is there a difference between both because my professor gave me a sample code and he had curly braces in there
• 02-23-2013
grumpy
The examples, as you have shown them, are equivalent.

The difference shows up if you have more than two statements.
Code:

```if (x == 0)     step_1();     step_2();```
will always execute step_2() regardless of the value of x (indentation of the code doesn't change that) whereas
Code:

```if (x == 0) {     step_1();     step_2(); }```
will not.

Also, be careful of
Code:

```if (x = 0)     cout<< x << "is 0" <<endl;```
as it does NOT test if x is zero. It assigns x to the value zero, and then does not produce any output. The equality test is == (two equal signs, not one).
• 02-23-2013
c++noob145
so let me get this clear

Code:

```if (x == 0)   cout << "Run this program"<<endl;     cout <<"Run this too"<<endl;```
Quote:

will always execute step_2() regardless of the value of x (indentation of the code doesn't change that) whereas
so it will display the statement "Run this too" if x is 1 and not 0
and both if x is 0. So basically step 2 in this one has nothing to do with the if statement before it?

Code:

```if (x == 0) {     cout << "Run this program"<<endl;     cout <<"Run this too"<<endl; }```
and this code will display both statements only if x = 0.
• 02-23-2013
Elkvis
Quote:

Originally Posted by c++noob145
and both if x is 0. So basically step 2 in this one has nothing to do with the if statement before it?

Code:

```if (x == 0) {     cout << "Run this program"<<endl;     cout <<"Run this too"<<endl; }```
and this code will display both statements only if x = 0.

exactly right. the compiler considers the first statement after the if to be the one controlled by it. a block of statements wrapped in curly brackets will be seen by the compiler as one statement, with respect to the if statement.
• 02-24-2013
rogster001
The curly braces give the ' scope ' of the IF statement - the number of instructions it encapsulates
• 02-24-2013
grumpy
Quote:

Originally Posted by rogster001
The curly braces give the ' scope ' of the IF statement - the number of instructions it encapsulates

No it doesn't. The scope of an if statement is something else entirely.

The curly braces are used to compose a single statement from multiple statements.