'=' assignment operator

how to put things and get things from the box

Variable Assignment

When a variable is declared, we can assign a value to the variable using the = (assignment operator). The first assignment to a variable is called the initialization. We should always initialize any variable we declare before reading them, as this is an "undefined behavior", the compiler may or may not crash from the consequences if you do so. We assign values like so:

int some_integer;
some_integer = 42;

char c;
c = 'A';

char d;
d = c;

In the above example, we set the value 42 to some_integer, which we assume is declared before. We also assigned a character, which must be quoted with single quotes, to c. 42 and 'A' are called literals, because they are basically the value.

Then, we assigned the value stored in c, to d, so d now has the value 'A'. Be careful, the = is not the mathematical "equal", it means "assign the RHS to the LHS".

Combined Declaration and Initialization

We may also combine the initialization with the declaration. The safest way to declare is always to first initialize to some default value.

int16_t some_integer = 42;
char c = 'A';
char d = c;

Here is a working program:

//variable.c

#include <stdio.h>
#include <stdint.h>

int main() {
    int16_t some_integer = 42;
    printf("The number is ");
    printf("%d", some_integer); //The left is used for formatting
    return 0;
    
    // Console:
    // The number is 42
}

Last updated