C memory managmentBasics
If Statements
If Statements in C
if
statements are the most basic form of control flow in C: very similar to
other languages. Basic syntax:
if (x > 3) {
printf("x is greater than 3\n");
}
if/else/else
if are also available:
if (x > 3) {
printf("x is greater than 3\n");
} else if (x == 3) {
printf("x is 3\n");
} else {
printf("x is less than 3\n");
}
Janky Syntax
You can write an if statement without braces if you only have one statement in the body:
if (x > 3) printf("x is greater than 3\n");
Example
#include <stdio.h>
char* cal_whether(int temp) {
if (temp < 70) {
return "too cold";
} else if (temp > 90) {
return "too hot";
} else {
return "just right";
}
}
int main() {
int temp = 91;
char* val = cal_whether(temp);
printf("temp is %d so it %s\n", temp, val);
temp = 69;
val = cal_whether(temp);
printf("temp is %d so it %s\n", temp, val);
temp = 75;
val = cal_whether(temp);
printf("temp is %d so it %s\n", temp, val);
return 0;
}
gcc main.c
./a.out
temp is 91 so it too hot
temp is 69 so it too cold
temp is 75 so it just right