Variables

Variables

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.

Basic Data Types

TypeDescriptionExample
intIntegerthe number 16
floatFloatthe decimal number 14.25
charCharacterthe single letter ‘A’
boolBooleantrue / false

What about strings?

There is no data type for a string.
Rather, it is an array of chars

Declaring a Variable

To declare a variable, we follow the syntax

<type> <variable_name>;


How would you declare a variable called mynumber with the integer type?

int mynumber;

Assigning a Variable

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;

Shortcut

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;

Reassigning Variables

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

Variable Naming

You can name your variable anything you want,
as long as it follows the rules

  • Only has the characters A-Z, A-Z, 0-9 and _
  • Does not start with a number
  • Is not a keyword (Reserved names)

 

my_var2my_var_3my_varmyv4rmy 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

Displaying Variables

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";

Next Steps

Strings

Home