Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyword for functions in C++?

Why doesn't C++ have a keyword to define/declare functions? Basically all other design abstractions in the language have one (struct, class, concept, module, ...).

Wouldn't it make the language easier to parse, as well as more consistent? Most "modern" languages seem to have gone this way (fn in rust, fun in kotlin, ...).

like image 406
Touloudou Avatar asked Jan 31 '20 08:01

Touloudou


People also ask

What is function syntax in C?

The syntax of creating function in c language is given below: return_type function_name(data_type parameter...){ //code to be executed. }

How do you declare a function in C?

Function Declarations The actual body of the function can be defined separately. int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.


1 Answers

C++'s Syntax comes mostly from C and C doesn't provide a function keyword. Instead, it uses a certain syntax to indicate most functions:

[return type] [function name]([paramters]) { } 

So if a function keyword was introduced, we could gain faster parsing and improve readibility. However, you would now have 2 different ways to declare something and you can' t get rid of the old way due to the backwards compability necessity.


But let's assume we ignore the backwards compability argument and suppose it was introduced:

function int square(int a) { //1
    return a * a; 
} 

//-----------------------------

function square(int a) { //2
    return a * a; 
} 

case 1 simply behaves like a keyword indicator, which has upsides (readiblity, parsing) and downsides (spamming the function declarations with unnecessary noise)

case 2 is a javascript-esque approach, letting the compiler figure out the return type (like auto here). it is probably the most esthetic approach, but C++ is very static typed and this would add a layer of confusion when it's not needed (auto-ness can be useful, but is certainly not always wanted).


So in the end it seems like these medium benefits just didn't justify the cost that would have came with introducing such a keyword.


extra bit:

since C++11 the language features would allow you to argue for a perticular approach:

function square(int a) -> int { 
    return a * a; 
} 

and this would certainly be a pretty solid solution! But it seems like the discussion about a function keyword has long subsided. Which is understandable when there are many other, probably more important, priorities to discuss while innovating on the newest C++ releases.

like image 158
Stack Danny Avatar answered Oct 12 '22 11:10

Stack Danny