Variables in C

Our first program will demonstrate how to declare and use variables in C. Here’s the full source code:

#include <stdio.h>
#include <stdbool.h>

int main() {
    // Declares a variable and initializes it
    char* a = "initial";
    printf("%s\n", a);

    // You can declare multiple variables at once
    int b = 1, c = 2;
    printf("%d %d\n", b, c);

    // C will infer the type of initialized variables
    bool d = true;
    printf("%d\n", d);

    // Variables declared without initialization are not guaranteed to be zero-valued
    // It's good practice to initialize them explicitly
    int e = 0;
    printf("%d\n", e);

    // C doesn't have a shorthand for declaration and initialization like ':='
    // You always use the standard declaration syntax
    char* f = "apple";
    printf("%s\n", f);

    return 0;
}

In C, variables are explicitly declared and used by the compiler to check type-correctness of function calls and operations.

char* declares a string (character pointer) variable.

You can declare multiple variables of the same type in one line.

C doesn’t have a built-in boolean type, but we can use #include <stdbool.h> to get the bool type.

Variables declared without initialization in C are not guaranteed to have a “zero value”. It’s good practice to initialize them explicitly.

C doesn’t have a shorthand syntax for declaring and initializing variables. You always use the standard declaration syntax.

To compile and run the program:

$ gcc variables.c -o variables
$ ./variables
initial
1 2
1
0
apple

This program demonstrates basic variable declaration and usage in C. Remember that C is a statically-typed language, so you need to declare the type of each variable explicitly.