In C, if is a keyword used to implement decision control instruction.
The condition following the keyword if is always enclosed within a pair of parentheses.
The general syntax of if statement looks like below:
Syntax of if statement:
1 2 3 4 5 6 |
if (condition) { statement; Or block of statements; } |
Above statement or block of statements will be executed when a condition is true. Otherwise, these statements get skipped.
Flowchart of if statement:
First of all, a condition is check and then, depending on whether the condition is true (‘non zero’) or false (‘zero’), it transfers the control to a particular statement.
If the condition is true then the statement inside the if block gets executed otherwise statements get skipped.
Example:
1 2 3 4 5 6 7 8 9 10 |
int main() { int a = 5; int b = 10; if (a < b) { printf("b is greater than a\n"); } printf("a is greater than b"); } |
Output:
1 2 |
b is greater than a a is greater than b |
Explanation:
In above program, if condition is true therefore the output is ‘b is greater than a’ and also ‘a is greater than b’ because statements execute after if statements.
Whereas, if a condition was false then the output will be only ‘a is greater than b’.
Examples:
1 2 3 4 |
if (condition) { printf("hi"); // hi } |
Condition will be any of the following to print output ‘hi’:
- constant
- string (“hello”)
- keyword (‘for’, ‘int’, sizeof(int))
- character (‘a’, ‘A’)
- Number (10, -600,)
- null character (null)
- NULL
- Logical expression (1 && 1)
- Arithmatic expression (5 + 2 % 5)
Forms of if statements
There are many forms of if statements, check out Forms of if: page for more details. These variations are used in different ways.