Guides:C/C Crash Course/if-else

From CoderGuide

Jump to: navigation, search

Back to TOC

The if, if-else statements, and logical operators

The if statement is pretty straight forward: If such and such, then go do such and such. It's that simple. A more complex form is: if such and such, then such and such, otherwise (else) do such and such. Simple eh? Well, this a little bit of a catch: we need to use something called logical operators to make comparisons between one number and another (or logical tests). Here's a list of them:

==equal to
 !=not equal to
>greater than
<less than
>=greater than or equal to
<=less than or equal to
&pipe;&pipe;or (logical)
and (logical)

Notice that two equal signs are used for the "equal to" logical test? That's because the single equal sign is the assignment operator and never performs a logical test. The GNU C/C++ compiler will warn you whenever you use the assignment operator within an if statement because, in most cases, you really intended to use the logical "equal to" operator, which is the double equal sign.

When these statements are evaluated, a value of 0 is returned if the statement is false, and a non-zero value is returned if the statement is true (often times it is 1). When all the logical statements are processed, and if the final answer is non-zero then the statement, or code block, after the if statement is processed, otherwise those in the else statement are processed if it exists.


#include <stdio.h>
int main(){
        int yaba,daba,poo;
        if(1) printf("This will always display\n");
        if(0) printf("This never will\n");
        else printf("\tBut this will\n"); /*the \t is an escape
                                            code for a tab */
        if(yaba!=daba)printf("Yaba doesn't equal daba\n");
        if( (yaba<daba) && poo==5){
                printf("Yaba is less than daba,");
                printf("and poo equals 5\n");
        }/*end if( (yaba...*/   
}/* end main() */
Personal tools