### Round brackets save the day!

While constructing logical statements in C/C++, you must care about telling C what you want. And you should tell it as clearly as possible. Thats where round brackets enter the scene. Take this for example -

int i = 2;In absence of proper parentheses, this code would result in telling you that 'i is equal to 5'.

if ( !i == 5 ) {

printf ( " i is not equal to 5 \n" );

} else {

printg ( " i is equal to 5 \n " );

}

What we wish to tell C is - Look, let i be 2. If (i==5) isn't the case, tell the user about it.

The problem is that "!i" means NOT(i), and C evaluates conditions from left to right.

So NOT(i) in this case is NOT(2) i.e. 1 ( or 10 become 01 in machine terms). Obviously 1 isn't equal to 5 and program ends up telling us that i is 5.

While if we use parentheses, the logic is better understood by C and any other programmer too.

int i = 2;

if ( ! ( i == 5) ) {

printf ( " i is not equal to 5 \n" );

} else {

printg ( " i is equal to 5 \n " );

}

Labels: programming

## 0 Comments:

## Post a Comment

Subscribe to Post Comments [Atom]

<< Home