The Wayback Machine - https://web.archive.org/web/20241129085521/https://www.geeksforgeeks.org/_generic-keyword-c/
Open In App

_Generics Keyword in C

Last Updated : 06 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The _Generic keyword in C is used to implement a generic code that can execute statements based on the type of arguments provided. It can be implemented with C macros to imitate function overloading. The _Generic keyword was first introduced in C11 Standard.

Syntax of _Generic in C

_Generic( (expression),
    type_1: statements,
    type_2: statements,
    .
    .
    default: statements
)

where,

  • expression: This test expression’s value type is used to determine which statements to execute.
  • default: Specifies the statement to be executed when no matching type is found.
  • type_1, type_2…: Types for which we have defined the genetic code.

The syntax may seem similar to the switch statement where we have different statements for different case values of the test expression.

How to use _Generic in C?

We can use the _Generic keyword anywhere in our code where we need some generic code. The below example demonstrates how to use _Generic keyword:

Example of _Generic

C




// C program to illustrate macro function.
#include <stdio.h>
int main(void)
{
    // _Generic keyword acts as a switch that chooses
    // operation based on data type of argument.
    printf("%d\n", _Generic(1.0L, float : 1, double : 2,
                            long double : 3, default : 0));
    
    printf("%d\n", _Generic(1L, float : 1, double : 2,
                            long double : 3, default : 0));
    
    printf("%d\n", _Generic(1.0L, float : 1, double : 2,
                            long double : 3));
    return 0;
}


Output

3
0
3

_Generic in Macros

A major drawback of Macro in C is that the arguments lack type checking, i.e. a macro can operate on different types of variables(like char, int, double,..) without type checking. We can use _Generic to include the statements for different argument types in such macros.

Example

C




// C program to illustrate macro function.
#include <stdio.h>
  
// Defining the macro with generic code for
//different argument types
#define geeks(T) _Generic((T), \
        char* : "String", \
        int : "Integer", \
        long : "Long Integer", \
        default : "Others")
  
int main(void)
{
  
    // Here A is a string.
    printf("%s\n", geeks("A"));
  
    // floating point value
    printf("%s\n", geeks(5));
    
      // float type which is not defined in the macro
      printf("%s", geeks(5.12));
  
    return 0;
}


Output

String
Integer
Others

As we can see, different expressions are returned for different datatypes. This behavior is similar to C++ function overloading where the parameter types specify which version of the function will be executed. So we can use the _Generic in C to provide some features of function overloading in our program.

Advantages of _Generic

Following are some main advantages of _Generic in C:

  • It can be used to stimulate function overloading when used with macros.
  • Allows the functionality to execute the code based on the type of parameters.

Disadvantages of _Generic

The major disadvantages of _Generic are as follows:

  • The major disadvantage of _Generic is its usage in macros as they are vulnerable to errors.
  • It is difficult to understand and debug in case of error due to complex syntax and limited view of expanded code.


Previous Article
Next Article

Similar Reads

C++ | Static Keyword | Question 1
Predict the output of following C++ program. #include <iostream> using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout << Test::getX() << " "; Test t[5]; cout << Test::getX(); } (A) 0 0 (B) 5 5 (C) 0 5 (D) Compiler Error Answer: (
1 min read
C++ | Static Keyword | Question 2
#include <iostream> using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout << p1.getID() << " "; cout << p2.getID() << " "; cout << p
1 min read
C++ | friend keyword | Question 1
Predict the output of following program. #include <iostream> using namespace std; class A { protected: int x; public: A() {x = 0;} friend void show(); }; class B: public A { public: B() : y (0) {} private: int y; }; void show() { A a; B b; cout << "The default value of A::x = " << a.x << " "; cout <
1 min read
C++ | friend keyword | Question 2
Predict the output the of following program. #include <iostream> using namespace std; class B; class A { int a; public: A():a(0) { } void show(A& x, B& y); }; class B { private: int b; public: B():b(0) { } friend void A::show(A& x, B& y); }; void A::show(A& x, B& y) { x.a = 10; cout << "A::a=" <<
1 min read
C++ | Static Keyword | Question 4
Predict the output of following C++ program. #include <iostream> using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout << b.get(); return 0; } (A) 0 (B) Linker Error: Undefined reference B::a
1 min read
C++ | const keyword | Question 1
Predict the output of following program #include <iostream> using namespace std; int main() { const char* p = "12345"; const char **q = &p; *q = "abcde"; const char *s = ++p; p = "XYZWVU"; cout << *++s; return 0; } (A) Compiler Error (B) c (C) b (D) Garbage Value Answer: (B) Explanation: Output is ‘c’ c
1 min read
C++ | const keyword | Question 2
In C++, const qualifier can be applied to 1) Member functions of a class 2) Function arguments 3) To a class data member which is declared as static 4) Reference variables (A) Only 1, 2 and 3 (B) Only 1, 2 and 4 (C) All (D) Only 1, 3 and 4 Answer: (C) Explanation: When a function is declared as const, it cannot modify data members of its class. Whe
1 min read
C++ | const keyword | Question 3
Predict the output of following program. #include <iostream> using namespace std; class Point { int x, y; public: Point(int i = 0, int j =0) { x = i; y = j; } int getX() const { return x; } int getY() {return y;} }; int main() { const Point t; cout << t.getX() << " "; cout << t.getY(); return 0; } (A) Garbage Value
1 min read
C++ | Static Keyword | Question 5
#include<iostream> using namespace std; class Test { private: static int count; public: Test& fun(); }; int Test::count = 0; Test& Test::fun() { Test::count++; cout << Test::count << " "; return *this; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } (A) Compiler Error (B) 4 4 4 4 (C) 1 1 1 1 (D) 1 2
1 min read
C++ | const keyword | Question 5
#include <stdio.h> int main() { const int x; x = 10; printf("%d", x); return 0; } (A) Compiler Error (B) 10 (C) 0 (D) Runtime Error Answer: (A) Explanation: One cannot change the value of 'const' variable except at the time of initialization. Compiler does check this.Quiz of this Question
1 min read
C++ | Static Keyword | Question 6
Output of following C++ program? #include <iostream> class Test { public: void fun(); }; static void Test::fun() { std::cout<<"fun() is static\n"; } int main() { Test::fun(); return 0; } Contributed by Pravasi Meet (A) fun() is static (B) Empty Screen (C) Compiler Error Answer: (C) Explanation: The above program fails in compi
1 min read
C++ | const keyword | Question 5
Output of C++ program? #include <iostream> int const s=9; int main() { std::cout << s; return 0; } Contributed by Pravasi Meet (A) 9 (B) Compiler Error Answer: (A) Explanation: The above program compiles & runs fine. Const keyword can be put after the variable type or before variable type. But most programmers prefer to put const ke
1 min read
Working of Keyword long in C programming
In C, long is a keyword that symbolizes the Long datatype. The long data type is a 64-bit two's complement integer with: Size: 64 bit Value: -263 to 263-1 The output of 64 bit GCC compiler would give the size of long as 8 whereas on 32 bit GCC compiler the size would be 4. So it varies from compiler to compiler. Now the question is what exactly is
3 min read
Use of explicit keyword in C++
Explicit Keyword in C++ is used to mark constructors to not implicitly convert types in C++. It is optional for constructors that take exactly one argument and work on constructors(with a single argument) since those are the only constructors that can be used in typecasting. Let's understand explicit keyword through an example. Predict the output o
3 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
C++ mutable keyword
The mutable storage class specifier in C++ (or use of mutable keyword in C++) auto, register, static and extern are the storage class specifiers in C. typedef is also considered as a storage class specifier in C. C++ also supports all these storage class specifiers. In addition to this C++, adds one important storage class specifier whose name is m
4 min read
restrict keyword in C
In the C programming language (after the C99 standard), a new keyword is introduced known as restrict. restrict keyword is mainly used in pointer declarations as a type qualifier for pointers.It doesn't add any new functionality. It is only a way for the programmer to inform about an optimization that the compiler can make.When we use restrict with
2 min read
Understanding "register" keyword in C
Registers are faster than memory to access, so the variables which are most frequently used in a C program can be put in registers using the register keyword. The keyword register hints to the compiler that a given variable can be put in a register. It's the compiler's choice to put it in a register or not. Generally, compilers themselves do optimi
3 min read
extern Keyword in C
extern keyword in C applies to C variables (data objects) and C functions. Basically, the extern keyword extends the visibility of the C variables and C functions. That's probably the reason why it was named extern. Though most people probably understand the difference between the "declaration" and the "definition" of a variable or function, for th
7 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations. As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example, If there is a
9 min read
Basics of File Handling in C
File handling in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program. Why do we need File Handling in C?So far the operations using the
15 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data types in C can be classified as follows: Types Description Data Types
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Article Tags :
three90RightbarBannerImg