cgenericsc11

Syntax and Sample Usage of _Generic in C11


I heard C11 added generics. I've googled a bit, looked at some articles, understood there's a new keyword ( _Generic ) and all. But I can't seem to grasp it all.

Is it something like the generics in C# or templates in C++? Can anyone give me a brief explanation of the C11 definition of generics, its syntax and a simple sample usage example?


Solution

  • This is a pretty good introduction. Here's the Overview:

    Generic selection is implemented with a new keyword: _Generic. The syntax is similar to a simple switch statement for types:_Generic( 'a', char: 1, int: 2, long: 3, default: 0) evaluates to 2 (character constants are ints in C).

    Basically it works like a kind of switch, where the labels are type names which are tested against the type of the first expression (the 'a' above). The result becomes the result of evaluating the _Generic().