CodeBlanks Logo Icon CodeBlanks

Summary - Modern C

Combine _Generic, _Static_assert and atomics to write a type-safe macro.

Summary - Modern C combined

In this lesson you'll combine _Generic, _Static_assert and atomics to write a type-safe macro. The safe_print macro uses _Generic to select the type, _Static_assert to verify int size, and an atomic_int counter to track calls.

Together these three features show the power of modern C: compile-time safety, type-based selection and thread-safe counting. You'll merge solutions from previous lessons into one program. The program prints the type name on each call and increments the counter; finally it prints the counter value.

Practice Write the safe_print macro

Add #include <stdatomic.h>. Write _Static_assert(sizeof(int) >= 4, "int en az 4 bayt");. Declare static atomic_int call_count = 0;. Write #define safe_print(x): select the type with _Generic((x), int: "int", double: "double", default: "diğer"), print via printf("%s\n", ...), then increment with atomic_fetch_add(&call_count, 1). In int main(void) call safe_print(42) and safe_print(3.14), finally print printf("%d\n", call_count).

Starter code

main.c
#include <stdio.h>
#include <stdatomic.h>

// derleme denetimi ekle
// atomik sayaç tanımla
// safe_print makrosunu yaz
// main'de çağır ve sayacı yazdır

Sample solution

main.c
#include <stdio.h>
#include <stdatomic.h>

_Static_assert(sizeof(int) >= 4, "int en az 4 bayt");
static atomic_int call_count = 0;

#define safe_print(x) printf("%s\n", _Generic((x), int: "int", double: "double", default: "diğer")); atomic_fetch_add(&call_count, 1)

int main(void) {
    safe_print(42);
    safe_print(3.14);
    printf("%d\n", call_count);
    return 0;
}

Expected output

int
double
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which three features does safe_print combine?

  • malloc, free, realloc
  • _Generic, _Static_assert, atomics Correct answer
  • printf, scanf, fprintf
  • fork, exec, wait

Explanation: safe_print combines _Generic + _Static_assert + atomics.

2 Complete the atomic increment call

Question
static atomic_int call_count = 0;
____(&call_count, 1);
Answer
static atomic_int call_count = 0;
atomic_fetch_add(&call_count, 1);

Explanation: atomic_fetch_add(&call_count, 1) atomically increments the counter.

3 Match feature to role

Term Meaning
_Generic Type selection
_Static_assert Compile check
atomic_int Atomic counter
printf Output writing

All lessons in Expert