Example of C if statement
This is an example C program illustrating the if
and else
statements.
#include <stdio.h> int main () { int i; /* This is always true. */ if (1) { printf ("This should be printed.\n"); } /* This is never true. */ if (0) { printf ("Something has happened to your computer.\n"); } /* We can also have "else". */ if (0) { printf ("This should not be printed.\n"); } else { printf ("This is the 'else' branch.\n"); } i = 1; /* One can leave off the { and } if there is only one statement. */ if (i == 1) printf ("This is a branch without the braces { and }.\n"); /* Can you spot the deliberate mistake? */ if (i = 100) printf ("Beware of equals signs in if statements.\n"); return 0; }
The output of the example looks like this:
This should be printed. This is the 'else' branch. This is a branch without the braces { and }. Beware of equals signs in if statements.
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer