When should I use if, if else, and else in C?
C did not invent the if clause. The principal is the same in most programming languages.
In general these are known as conditional statements. They allow your program logic to branch to different behaviors based upon the value of some data.
For instance, if a particular class at school requires a grade of 70% to pass one can state:
if (grade >= 70) {
printf(“Passed”);
}
else {
print(“Failed”);
}
The else if construct is used when there are several values to act upon differently.
The else clause is used when none of your “if” or “else if” clauses are true.
If only one of several options can happen, you use if
/ else
structure, if
/ else if
structure, if
/ else if
/ else
structure or switch
/ case
structure:
- if (a == 3) {
- b++;
- }
- else if (a < 1) {
- c++;
- }
- else {
- b = c = 0;
- }
If several options can happen, you use if
structure:
- if (a == 3) {
- b++;
- }
- if (b < 1) {
- c++;
- }
depends on the situation
if you are going to chec integers on a single one by one the switch is far better.
if you have a lot on the else with some if then if else (with {}) and inside more if if you need
if lots of conditional of < or similar al loop if possible if not , if else is ok.