Variables are containers that hold data.
This data could be a number, name, etc…
In some languages variables can hold any type of data, then be replaced with a different type.
However the C language is ‘statically typed’, meaning that each variable accept only a specific type of data.
Type | Description | Example |
---|---|---|
int | Integer | the number 16 |
float | Float | the decimal number 14.25 |
char | Character | the single letter ‘A’ |
bool | Boolean | true / false |
What about strings?
There is no data type for a string.
Rather, it is an array of char
s
To declare a variable, we follow the syntax
<type> <variable_name>;
How would you declare a variable called mynumber
with the int
eger type?
int mynumber;
To set a variable to a particular value, we use the assignment operator ‘=
‘
<variable_name> = <value>;
How would you declare a variable mynumber
with the int
type, and then assign it the number 30
?int mynumber;
mynumber = 30;
Declaring variables and immediately assigning a value to them is a very common practice.
The C language allows us to declare and assign a variable in one line!
int mynumber = 30;
We can easily change the value of a variable by assigning it a new value!
int number = 10; // number is 10
number = 5; // number is now 5
number = 13; // number is now 13
NOTE: We only define the type of a variable ONCE
You can name your variable anything you want,
as long as it follows the rules
A
-Z
, A-Z
, 0-9
and _
my_var | 2my_var | _3my_var | myv4r | my var5 |
---|---|---|---|---|
✔️ | ❌ | ✔️ | ✔️ | ❌ |
Note: Variables are case-sensitive.
my_var
is different to My_var
int | float | char | bool
How would you define a variable for the age of someone who is 15
?
int age = 15;
How would you define a variable to contain the temperature 19.35
°C?
float temperature = 19.35;
How would you define a variable to be false
?
bool result = false;
How would you define a variable for the letter H
?
char letter = ‘H’;
Note: You need to wrap the letter with apostrophes
We can use printf
to show variables!
#include <stdio.h>
int main(void) {
int num;
num = 12;
char c = 'm';
printf("num is %d, and c is %c\n", num, c);
num = 10;
printf("num is now %d", num);
return 0;
}
$> ./program
num is 12, and c is m
num is now 10
How would you define a variable for the word Hello
?
char word = 'Hello';
char word = "Hello";
string word = "Hello";
char word[] = "Hello";