What is _Generic keyword in C?

The Generic keyword provides a way to select an expression in a generic association table at compile-time, based on the type of assignment expression. Using Generic, we can abstract different functions with the same functionality as a unified interface to provide generality.

Syntax

_Generic ( assignment-expression, generic-assoc-list )

Parameters

assignment-expression: An assignment expression that can be considered a variable.

generic-assoc-list: A generic association table whose syntax is:

type-name : expression, type-name : expression, ...,

Code

#include <stdio.h>
#define TYPE_NAME(X) _Generic((X), \
int: "Integer", \
char: "Character", \
double: "Double", \
default: "Unknown")
int main()
{
printf("Type Name: %s\n", TYPE_NAME(42)); //Checks the type of the given input
}

In this code, we have data types such as int, char, double, and a default value defined for Generic. When TYPE_NAME is called with the argument 42, its data type is checked against the types defined by Generic (int in this example). The value associated with the matched data type, "Integer" is then returned.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved