C Tutorial
C Enums
enum names a set of integer constants so you write RED instead of a magic number.
Names instead of magic numbers
A traffic light is not “0 or 1” in your head. It is red or green. If you store int light = 1;, every reader has to remember what 1 means. An enum gives those integers names the compiler understands.
Write enum Color { Red, Green };. The names live in the surrounding scope: you writeRed, not a dotted prefix. Declare a variable as enum Color light;.
Write an enum
List the names in braces. The compiler assigns integers starting at zero unless you set them yourself. You almost never need the integers. You need the names.
Example
#include <stdio.h>
enum Color { Red, Green };
int main(void) {
enum Color light = Green;
if (light == Green) {
printf("go\n");
}
light = Red;
if (light == Red) {
printf("stop\n");
}
return 0;
}Compare with ==. Assign with =. Put the enum definition above main, the same way you did with struct.
switch on an enum
A switch is a good fit when every value of the enum should take a different path. Write acase for each enumerator. Put break; at the end of each case so execution does not fall through.
Example
#include <stdio.h>
enum Color { Red, Green };
int main(void) {
enum Color light = Red;
switch (light) {
case Red:
printf("halt\n");
break;
case Green:
printf("proceed\n");
break;
default:
printf("unknown\n");
break;
}
return 0;
}Change light in /c/try. Try Red and Green. Keep a break on each case.
The integers are still there
Under the hood, Red is 0 and Green is 1. You can set your own numbers if a file format or a protocol requires them:enum Status { Ok = 200, NotFound = 404 };.
Example
#include <stdio.h>
enum Status { Ok = 200, NotFound = 404 };
int main(void) {
enum Status code = NotFound;
if (code == Ok) {
printf("ready\n");
} else {
printf("missing\n");
}
printf("stored as %d\n", code);
return 0;
}In C an enum value is an integer. printf("%d", code) prints the number. Prefer comparing to other enumerators. Leave the integers for storage and debugging.
Where enums fit
Use an enum for a closed set of choices: a color, a status, a difficulty, a day of the week. Do not use it for values that grow without a fixed list, such as a player’s score. That is still an int.
| Piece | Role |
|---|---|
enum Color { Red, Green }; | Names the constants |
enum Color light; | Declares a variable of that type |
light = Green; | Stores one enumerator |
Enumerator names are not scoped inside the type. Two enums in the same file cannot both have aRed. Pick names that will not collide.
Next: a union stores one of several types in the same memory.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C editor at /c/try. Change one measurement and check whether the result still has the right unit.
Chemistry
Named phases
Solid, liquid, gas are not 0, 1, 2 in nature. They are names. enum lets the program use GAS while the machine still stores a small integer. By default SOLID is 0, LIQUID 1, GAS 2.
if (water == GAS) reads like the sentence in the textbook. if (water == 2) does not.
Example
#include <stdio.h>
int main(void) {
enum Phase { SOLID, LIQUID, GAS };
enum Phase water = GAS;
printf("code = %d\n", water);
if (water == GAS) {
printf("steam\n");
}
return 0;
}Physics
Open or closed circuit
A switch is a two-state device. Current needs a closed loop. OPEN and CLOSED as enum values stop you mixing 0/1 with some other flag in the same file.
The print is the physics: closed means charges can move. It is not a moral judgement about the switch.
Example
#include <stdio.h>
int main(void) {
enum Circuit { OPEN, CLOSED };
enum Circuit lamp = CLOSED;
printf("%s\n", lamp == CLOSED ? "current can flow" : "open circuit");
return 0;
}