Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C11 type-generic expressions - why not just add function overloading?

Tags:

I was just reading the Wikipedia article on C11, the new version of the C standard released in Dec 2011, and I saw that one of the added features was "type-generic expressions":

Type-generic expressions using the _Generic keyword. For example, the following macro cbrt(x) translates to cbrtl(x), cbrt(x) or cbrtf(x) depending on the type of x:

#define cbrt(X) _Generic((X), long double: cbrtl, \                               default: cbrt, \                               float: cbrtf)(X) 

This looks pretty horrible to me - if they are going to change the language anyways, why not just add function overloading like in C++?

like image 562
HighCommander4 Avatar asked Jan 07 '12 23:01

HighCommander4


People also ask

Can C support function overloading?

No, C doesn't support any form of overloading (unless you count the fact that the built-in operators are overloaded already, to be a form of overloading). printf works using a feature called varargs.

What is Generic selection in C?

A generic selection is a primary expression. Its type and value depend on the selected generic association. The following diagram shows the generic selection syntax: _Generic ( assignment-expression , , type-name : assignment-expression default : assignment-expression 1 )

Does function overloading imply?

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.


1 Answers

C has one namespace for external symbols, and applies the ODR (One Definition Rule) such that two extern objects with the same name in two translation units must have the same definition.

Although it's possible to create a C ABI that supports overloading, the main strength of C is its ABI simplicity. On almost all platforms "the" ABI is the C ABI, and it plays some role in execution no matter the source language. This would be lost if symbols had to include type information.

TGE (as used by the library) is just a manually-operated version of name mangling. It does (or will do, sometime in the possibly very distant future) the job it needs to do, to allow typedef declarations to control generation of math-intensive inner loops. People who need the features of a language like C++ should port to C++.

like image 60
Potatoswatter Avatar answered Oct 17 '22 15:10

Potatoswatter