0Pricing
C Academy · Lesson

Type Safety Concerns

Risks of variadics.

Variadics bypass type checking

Normal C functions check that arguments match parameter types. Variadic arguments skip this check entirely.

The compiler cannot verify what you pass after the ..., which makes mistakes easy and dangerous.

#include <stdio.h>
#include <stdarg.h>

int add(int n, ...) {
    va_list a; va_start(a, n);
    int s = 0;
    for (int i = 0; i < n; i++) s += va_arg(a, int);
    va_end(a);
    return s;
}

int main(void) {
    printf("%d\n", add(2, 3, 4));
    return 0;
}

Wrong type in va_arg

If you read an argument with the wrong type, the result is undefined behavior.

Passing an int but reading it as a double reinterprets unrelated bytes and produces garbage or a crash.

#include <stdio.h>
#include <stdarg.h>

int read_int(int n, ...) {
    va_list a; va_start(a, n);
    int v = va_arg(a, int);
    va_end(a);
    return v;
}

int main(void) {
    printf("%d\n", read_int(1, 100));
    return 0;
}

All lessons in this course

  1. The stdarg Macros
  2. Writing printf-like Functions
  3. Type Safety Concerns
  4. Practical Examples
← Back to C Academy