CC

C: Basics – code examples

Contents

Hello World

Basics#printf#main#outputCompare in all languages
Use case: A first test of whether the compiler and environment work.
#include <stdio.h>

int main(void) {
    printf("Hello World!\n");
    return 0;
}

main is the entry point, printf prints text. Without \n there would be no line break. Compile with: gcc -Wall -o hallo hallo.c.

Variables and types

Basics#variable#type#sizeofCompare in all languages
Use case: Store values and check their size in memory.
#include <stdio.h>
#include <stdbool.h>

int main(void) {
    const char *name = "Ada";
    int alter = 36;
    double groesse = 1.68;
    bool aktiv = true;
    printf("%s %d %.2f %d\n", name, alter, groesse, aktiv);
    printf("%zu %zu\n", sizeof(alter), sizeof(groesse));
    return 0;
}

Every variable has a fixed type. The format string determines the output (%s string, %d int, %f double). sizeof returns bytes (typically 4 and 8).

Random numbers (dice)

Basics#rand#srand#random#time
Use case: Games, simulations or test data with random values.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand((unsigned)time(NULL));     // set the seed only ONCE
    for (int i = 0; i < 5; i++) {
        printf("%d ", rand() % 6 + 1);
    }
    printf("\n");
    return 0;
}

rand() returns pseudo-random numbers; srand sets the seed (here: the current time). Unsuitable for cryptography – use system-specific sources such as /dev/urandom for that.

Printing the sizes of the basic types

Basics#sizeof#types#portability
Use case: Check how wide types really are on the target platform (portability, file formats).
#include <stdio.h>

int main(void) {
    printf("char:      %zu\n", sizeof(char));
    printf("short:     %zu\n", sizeof(short));
    printf("int:       %zu\n", sizeof(int));
    printf("long:      %zu\n", sizeof(long));
    printf("long long: %zu\n", sizeof(long long));
    printf("float:     %zu\n", sizeof(float));
    printf("double:    %zu\n", sizeof(double));
    printf("void *:    %zu\n", sizeof(void *));
    return 0;
}

On common 64-bit systems: 1, 2, 4, 8 (Linux/macOS) or 4 (Windows), 8, 4, 8, 8. The standard only guarantees minimum sizes – use <stdint.h> for fixed widths.