Variables and types
Programs need to remember things: a test score, the price of an item, how many boxes are left in stock. A variable is a named box that holds a value. In C, before you use a variable you have to say two things: what it is called, and what kind of value it holds.
1#include <stdio.h>2 3int main(void) {4 int score = 90;5 printf("Score: %d\n", score);6 return 0;7}
Score: 90
int score = 90; means: give me a box for a whole number (int), call it score, and put 90 in it. The %d inside printf is a placeholder. When the text is shown, it is replaced by the value of score, which comes after the comma.
Declare and assign
int stock; is a declaration: it tells the compiler there is a variable called stock that holds whole numbers. stock = 12; is an assignment: it puts a value in the box. You can write the two steps apart, or join them in one line as above. A variable has to be declared before any statement uses it.
1#include <stdio.h>2 3int main(void) {4 int stock;5 stock = 12;6 printf("Stock: %d\n", stock);7 stock = 7;8 printf("Stock: %d\n", stock);9 return 0;10}
Stock: 12 Stock: 7
You can assign as many times as you like; the new value replaces the old one. In C, = does not mean "equals". It means "put the value on the right into the variable on the left". Press Step and watch stock change from 12 to 7.
What does this print?
1#include <stdio.h>2 3int main(void) {4 int a = 5;5 int b = a;6 a = 9;7 printf("%d\n", b);8 return 0;9}
int b = a; copies the value a has at that moment, 5, into b. Later a becomes 9, but the 5 in b doesn't change with it.
Three basic types
Every variable in C has a fixed type. You write it before the name when you declare it, and it can't change later. Here are the three you will use most:
| Type | Holds | Examples | printf uses |
|---|---|---|---|
int | whole numbers | 90, -3, 0 | %d |
double | numbers with a decimal point | 4.5, -0.25 | %f |
char | one character, in single quotes | 'A', '7', '?' | %c |
1#include <stdio.h>2 3int main(void) {4 int count = 3;5 double price = 4.5;6 char grade = 'A';7 printf("Count: %d\n", count);8 printf("Price: %f\n", price);9 printf("Grade: %c\n", grade);10 return 0;11}
Count: 3 Price: 4.500000 Grade: A
By default %f shows 6 decimal places, so 4.5 comes out as 4.500000. Lesson 3 shows how to get just two. A char holds one letter, digit or symbol. Many characters from other languages don't fit in a single char; lesson 13 explains why.
What happens if you put a number with decimals into an int?
What does this print?
1#include <stdio.h>2 3int main(void) {4 int people = 3.9;5 printf("%d\n", people);6 return 0;7}
An int holds only whole numbers. When 3.9 goes in, the decimal part is simply dropped, not rounded, so you get 3.
Several values in one printf
One printf can hold several format specifiers. The values come after it, separated by commas, and are matched one by one, in order:
1#include <stdio.h>2 3int main(void) {4 int day = 3;5 int steps = 8500;6 double temp = 21.5;7 printf("Day %d: walked %d steps, temperature %f degrees\n", day, steps, temp);8 return 0;9}
Day 3: walked 8500 steps, temperature 21.500000 degrees
The first %d becomes day, the second %d becomes steps, and %f becomes temp. Each format specifier has to match the type of its value: %d goes with int, %f with double, %c with char. If they don't match, what you see is garbage, and the compiler usually gives a warning.
Assign before you use
If you declare a variable but never give it a value, what is in the box? C doesn't say. It could be any number, and it might differ from one run to the next. Using such a value is undefined behavior. On an ordinary computer the program would just carry on and show some strange number. Our engine stops at the line where it happens and tells you what went wrong:
1#include <stdio.h>2 3int main(void) {4 int total;5 printf("Total: %d\n", total);6 return 0;7}
use of uninitialized valueWhat happened: Stopped at line 5. A variable was used before it was given a value. In real C it would hold garbage, different on every run.
The fix is simple: give it a value when you declare it, for example int total = 0;.
Tip: Give every variable a value when you declare it, and this mistake can't happen.
sizeof: how much room
A value of each type takes a fixed number of bytes in memory. sizeof tells you how many, for a type or for a variable. Print its result with %zu. Each number below is a count of bytes:
1#include <stdio.h>2 3int main(void) {4 int score = 90;5 printf("int: %zu\n", sizeof(int));6 printf("double: %zu\n", sizeof(double));7 printf("char: %zu\n", sizeof(char));8 printf("score: %zu\n", sizeof score);9 return 0;10}
int: 4 double: 8 char: 1 score: 4
A char is always 1 byte. The sizes of int and double can differ from one computer to another, but on the computers you will usually meet they are 4 and 8. The number of bytes decides how big a number fits: a 4-byte int goes up to about 2.1 billion. Lesson 4 shows what happens when you go past that.
Constants with const
Some values should never change once set, like the number of days in a week. Put const in front of the declaration and the variable becomes a constant. If anything tries to change it later, the compiler refuses:
1#include <stdio.h>2 3int main(void) {4 const int DAYS_IN_WEEK = 7;5 printf("A week has %d days\n", DAYS_IN_WEEK);6 DAYS_IN_WEEK = 8;7 return 0;8}
main.c: In function 'main':
main.c:6:18: error: assignment of read-only variable 'DAYS_IN_WEEK'
6 | DAYS_IN_WEEK = 8;
| ^A read-only variable can be read but not changed. Constants are usually named with capital letters and underscores, so you can tell them from ordinary variables at a glance. Remove the last assignment and the program runs.
Naming rules
A variable name is made of letters, digits and the underscore _, and a few rules apply:
| Rule | OK | Not OK |
|---|---|---|
Only letters, digits and _ | total_price | total-price |
| Can't start with a digit | day2 | 2day |
| No spaces | max_score | max score |
| Not one of C's own words | count | int |
Also, capital and small letters are different, so score and Score are two separate variables:
1#include <stdio.h>2 3int main(void) {4 int score = 90;5 int Score = 60;6 printf("%d and %d\n", score, Score);7 return 0;8}
90 and 60
Just because you can doesn't mean you should: two names that differ only in case are easy to mix up. The usual habit is small letters with underscores between words, and a name that says what the variable holds: price is better than p, and max_score is better than ms.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Your first variable
✓Declare an int variable age with the value 30, then use it to print Age: 30.
Age: 30
1#include <stdio.h>2 3int main(void) {4 5 return 0;6}
Three types
✓Using one printf and these three variables, print Size M, 19.900000 each, 2 items.
Size M, 19.900000 each, 2 items
1#include <stdio.h>2 3int main(void) {4 char size = 'M';5 double price = 19.9;6 int count = 2;7 8 return 0;9}
Fix it
✓This program doesn't compile. Fix it so it prints Stock: 12.
Stock: 12
1#include <stdio.h>2 3int main(void) {4 printf("Stock: %d\n", stock);5 int stock = 12;6 return 0;7}
What you learned
- Declare a variable before using it:
int stock;declares,stock = 12;assigns, or join them asint stock = 12;. =puts the value on the right into the variable on the left; assigning again replaces the old value.intholds whole numbers,doublenumbers with decimals,charone character;printfuses%d,%fand%cfor them.- Using a variable that was never given a value is undefined behavior; give it a value when you declare it.
sizeoftells you how many bytes a type or variable takes; print it with%zu.constmakes a variable a constant; changing it is a compile error.- Names use letters, digits and
_, don't start with a digit, aren't C's own words, and case matters.