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, ...).
The syntax of creating function in c language is given below: return_type function_name(data_type parameter...){ //code to be executed. }
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With