Skip to content
  • Variables, Constants & Literals · C

Variables, Constants & Literals

LearnViaNotes @learnvianotes· 3 min read

A variable is a named, typed region of memory. C gives you three kinds of constants: literals, const objects, and #define / enum names.

Declaring and initialising

C
#include <stdio.h>

int main(void) {
    int a = 10, b = 20;        /* several on one line */
    double ratio = a / (double)b;
    char grade = 'A';
    int uninit;                /* indeterminate value — do not read it! */
    uninit = 5;                /* assign before use */
    printf("%d %d %.2f %c %d\n", a, b, ratio, grade, uninit);
    return 0;
}
Output
10 20 0.50 A 5

Identifier rules

  • Letters, digits and _; cannot start with a digit; case-sensitive (count ≠ Count).

  • Cannot be a keyword (int, return, static, sizeof…).

  • Names starting with _ + uppercase letter or __ are reserved for the implementation — don’t use them.

  • Convention: snake_case for variables and functions, UPPER_CASE for macros and constants.

Literals

LiteralTypeExample
Decimal / octal / hex integerint (or larger if needed)42, 052, 0x2A
Suffixes u, l, llunsigned, long, long long42u, 42L, 42ULL
Floatingdouble by default3.14, 1e-3, 2.5f (float), 2.5L (long double)
Characterint (!)'A', '\n', '\0', '\x41'
Stringchar[N] (array incl. NUL)"hi" has 3 bytes
Compound (C99)unnamed object(int[]){1, 2, 3}
C
#include <stdio.h>

int main(void) {
    printf("%d %d %d\n", 42, 052, 0x2A);         /* same number, three bases */
    printf("%zu %zu %zu\n", sizeof 42, sizeof 42L, sizeof 42.0f);
    printf("[%s] has %zu bytes\n", "hi", sizeof "hi");
    printf("tab[\t] quote[\"] backslash[\\] newline next:\n.\n");
    return 0;
}
Output
42 42 42
4 8 4
[hi] has 3 bytes
tab[	] quote["] backslash[\] newline next:
.

Three ways to name a constant

FormExampleTyped?ScopeNotes
#define#define MAX 100NoFrom definition to end of fileText substitution by the preprocessor; no address
constconst int max = 100;YesBlock / fileA read-only variable; not a constant expression in C (can’t size a global array)
enumenum { MAX = 100 };intBlock / fileA true integer constant expression, visible to the debugger
C
#include <stdio.h>

#define PI 3.14159
enum { SIZE = 4 };

int main(void) {
    const int answer = 42;
    int arr[SIZE] = {1, 2, 3, 4};           /* enum constant can size an array */
    printf("%.2f %d %d\n", PI * 2, answer, arr[SIZE - 1]);
    return 0;
}
Output
6.28 42 4
C — modifying a const is a compile error
int main(void) {
    const int limit = 10;
    limit = 20;              /* error: cannot assign to a const-qualified variable */
    return limit;
}

What is the difference between #define and const?

What value does an uninitialised variable have?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report