Naming rules
C is strict about names. A variable name:
- can use letters, digits and the underscore
_, - cannot start with a digit (
2catsis not allowed,cats2is fine), - cannot contain spaces or symbols like
-or!, - cannot be a C keyword such as
int,returnorif, - is case-sensitive:
scoreandScoreare two different variables.
Good habits
Choose names that say what the value means:
#include <stdio.h>
int main() {
int x = 60; // what is x? nobody knows
int y = 3;
int minutesPerHour = 60; // much clearer!
int hours = 3;
printf("%d %d\n", x * y, minutesPerHour * hours);
return 0;
}Output
180 180
Two popular styles for names made of several words: camelCase (totalPrice) and snake_case (total_price). Pick one and stick with it.
Constants with #define
Some values never change, like the number of days in a week. The classic C way is #define. It goes at the top, under the #include lines, and has no = and no ;:
#include <stdio.h>
#define DAYS_IN_WEEK 7
#define PI 3.14159
int main() {
printf("Days in 4 weeks: %d\n", 4 * DAYS_IN_WEEK);
printf("PI is about %.2f\n", PI);
return 0;
}Output
Days in 4 weeks: 28 PI is about 3.14
Before compiling, C replaces every DAYS_IN_WEEK in your code with 7. If the value ever changes, you only edit one line.
Constants with const
Another way is to put const in front of a normal variable. Then C refuses to let anyone change it:
#include <stdio.h>
int main() {
const int MAX_PLAYERS = 4;
printf("Up to %d players\n", MAX_PLAYERS);
return 0;
}Output (on your own computer with gcc – the simple C runner in the browser editor can't run this one)
Up to 4 players
If you try to change a const variable, the program won't compile:
#include <stdio.h>
int main() {
const int MAX_PLAYERS = 4;
MAX_PLAYERS = 5;
return 0;
}Output (the program does not compile) (on your own computer with gcc – the simple C runner in the browser editor can't run this one)
main.c:5:17: error: assignment of read-only variable ‘MAX_PLAYERS’
Tip: The simple C runner in our browser editor doesn't understand
const, so in the challenges use#definefor constants.
Remember: Constants are usually written in CAPITAL_LETTERS so they stand out.