Initialization and Assignment
Declaring a variable and then storing a value in it takes two lines. You can do both in one:
int age = 15;Giving a variable a value when you create it is called initialization. This course creates variables this way, because then you can see what is in a variable from the very start.
Later, you can store a different value in the variable. That's called assignment. Write the name, = and the new value, but without the data type, because the variable already exists:
int score = 0;
printf("Score: %d\n", score);
score = 50;
printf("Score: %d\n", score);This prints:
Score: 0
Score: 50A program runs its statements one after another, from top to bottom. When the first printf runs, score holds 0. The next line replaces it with 50, and the old value is gone. So the second printf prints the new value.
A common mistake is to write the data type again when you assign a value: int score = 50;. That would create a second variable with the same name, and C doesn't allow that. The compiler reports redefinition of 'score': you are defining the name score a second time.
Another mistake is to use a variable before it has a value:
#include <stdio.h>
int main(void) {
int score;
printf("Score: %d\n", score);
return 0;
}The compiler reports:
main.c:5:27: error: variable 'score' is uninitialized when used here [-Werror,-Wuninitialized]Uninitialized means that the variable hasn't got a value yet. The part in square brackets only says which of the compiler's checks found the problem; you can ignore it. Below the first line, the compiler even shows where to add a value (= 0).
Why is this an error? C itself doesn't say what a variable without a value holds. On another computer, this program could print 0, or 21845, or a different number every time. A mistake like that is hard to find, so the compiler on this site doesn't let it through. The safest way to avoid it is to give every variable a value when you create it.
Instructions
- 1
Run the program. It doesn't compile, because
temperaturehas no value. Initialize it: give it the value12when you create it. Then the program printsMorning: 12 degrees. - 2
In the afternoon, it got warmer. Below the
printf, assign the new value18totemperature. - 3
Below it, print the new value the same way, but with
Afternooninstead ofMorning. The program should print:Morning: 12 degrees Afternoon: 18 degrees