DMarlon Studio

Lesson 2 · 2 of 20

Variables and basic types · C

Declare variables in C with the int, double and char types, change their values, use const and check with sizeof how many bytes each type takes.

C · Variables and basic types in DMarlon Studio: the example's code and its output in the terminal

A variable is a named piece of memory. In C you have to declare it with its type before using it: int apples = 12; creates a whole-number variable called apples and gives it the value 12.

The three basic types in the example are `int` for whole numbers, `double` for numbers with decimals (1.35) and `char` for a single character, written between single quotes: 'A'. The type decides what fits in the variable and how printf writes it: %d for int, %f for double and %c for char.

A variable can change its value: apples = apples - 3; first works out 12 - 3 and then stores the result, 9, in the same variable. You can also create a variable from others, like total.

With `const` the value is fixed: if you tried to change vat later, the compiler would refuse. Finally, `sizeof` tells you how many bytes each type takes; it is printed with %zu. Notice that %f shows six decimals: lesson 4 shows how to choose how many.

Code · main.c

#include <stdio.h>int main(void) {    // int: whole numbers    int apples = 12;    int pears = 7;    // double: numbers with decimals    double price = 1.35;    // char: a single character, between single quotes    char grade = 'A';    printf("Apples: %d\n", apples);    printf("Pears: %d\n", pears);    printf("Price per kilo: %f\n", price);    printf("Quality grade: %c\n", grade);    // A variable can change its value.    apples = apples - 3;    printf("Apples after selling 3: %d\n", apples);    // A new variable can be calculated from others.    int total = apples + pears;    printf("Pieces of fruit: %d\n", total);    // const: a value that cannot change.    const double vat = 0.21;    printf("Price with VAT: %f\n", price + price * vat);    // sizeof tells how many bytes each type uses.    printf("int: %zu bytes, double: %zu, char: %zu\n",           sizeof(int), sizeof(double), sizeof(char));    return 0;}

Output · cc main.c -o main && ./main

Apples: 12
Pears: 7
Price per kilo: 1.350000
Quality grade: A
Apples after selling 3: 9
Pieces of fruit: 16
Price with VAT: 1.633500
int: 4 bytes, double: 8, char: 1

Key points

  • In C every variable is declared with its type.
  • int whole numbers, double decimals, char one character in ' '.
  • = stores a value; the variable can change later.
  • const stops the value from changing.
  • sizeof gives the size in bytes.

Exercise

Add a double variable with the weight of the pears in kilos and print how much they cost at price euros a kilo.