There are a few legal ways which can we declare a function in C++.
Some of the legal ways are:
void function ();
void function (void);
dataType function (dataType);
and so on...
Recently, I came across a function declaration as such:
void (function) (); //Take note of the braces around the function name
I have never seen somehting like this before, when I tested it in a C++ compiler, it runs without any warning or compilation errors.
My question is: Why is void (function) (); a legal way to decalre a function prototype? Is there any special meaning to declare a function in this way? Or does it just work normally like any other function declaration?
One difference is that enclosing it in parenthesis prevents the function-like macros expansion by the preprocessor. As mentioned in the other answers it makes no difference though to the actual compiler.
For instance:
// somewhere buried deep in a header
#define function(a, b) a + b
// your code
void function() { // this expands the macro and gives compilation error
}
void (function)() { // this does not expand and works as expected
}
This comes in handy for instance when the bright minds behind the Microsoft Visual Studio library decided to provide function-like macros for things like min and max. (There are other ways like #undef to go around this).
Note that object-like macros (e.g. #define function 3 + 4) are still expanded.
The preprocessor is just a dumb text replacement tool (as opposed to the compiler which is just a (smart) text replacement tool). It takes the macro definition and replaces it everywhere. He is not aware of the semantics of what he replaces.
For instance:
// somewhere buried deep in a header
#define function 3 + 2
// your code
void function() {
}
The preprocessor sees the word function and textually replaces it with the string 3 + 2. He is unaware that function is a id-name part of a function declaration and definition. After the preprocess phase there come the actual compile phases. So the compiler actually sees:
// your code
void 3 + 2() {
}
which does not make any sense to him and gives an error.
For function-like macros
// somewhere buried deep in a header
#define function(a, b) a + b
The preprocessor does the same except that it expects two ‘tokens’ enclosed in parenthesis separated by comma (the parameters) and does the replacement. (again no semantics aware):
int d = function(2, 3);
//will be replaced by the preprocessor to:
int d = 2 + 3; // passes compilation phase
void function();
// the preprocessor doesn’t find the arguments for function so it gives an error.
However if it encounters (function) it will not try to expand it (it ignores it). It is just a rule.
it's the same as
void function();
you can declare it as
void ((function)) ();
if you want :)
be careful not to mix this up with the function pointer declaration syntax.
There is nothing special about it, it means exactly the same as the version without parentheses. It is just an artifact of how the syntax is declared. Usually you see the use of parentheses around the function name when a function pointer is declared, e.g.
void (*function_pointer)() = nullptr;
// a function pointer to a function taking and returning void
in contrast to
void *function();
// a function declaration of a function taking void and returning void*
I think it works the same as a normal function because function pointers are declared like: void (*function)() so if you leave out the * then it should be just a function.
It corresponds to the C++ grammar. If to simplify then one of the rules for defining of the declarator looks as
declarator:
(declarator)
So you can write for example
void (function) ();
or
void ( (function) () );
or even the following way
struct A
{
void ( ( function )() const );
};
I think you may find that was:
void (*function) ();
since there is no benefit to using void (function)(); or void (((((function)))))(); for that matter, they're equivalent. If I'm mistaken and it's not a typo, the answer is that you can put as many parentheses around the function name as you like, subject to compiler limitations, as per the code for output6() below.
If I'm not mistaken, that one with the * actually declares a function pointer which can be used to hold a pointer to a function. It does not declare a function at all, just a pointer that can be used to reference a function.
Like an int pointer (for example), the function pointer can point to an arbitrary function, parameters notwhithstanding.
So for example:
#include <iostream>
void (((((output6)))))() { std::cout << 6; }
void output7() { std::cout << 7; }
void output8() { std::cout << 8; }
void (*fn)();
int main() {
fn = &output6; fn();
fn = &output7; fn();
fn = &output8; fn();
std::cout << '\n';
}
would output 678.
Related
I was taught that functions need declarations to be called. To illustrate, the following example would give me an error as there is no declaration for the function sum:
#include <iostream>
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
// main.cpp:4:36: error: use of undeclared identifier 'sum'
// std::cout << "The result is " << sum(1, 2);
// ^
// 1 error generated.
To fix this, I'd add the declaration:
#include <iostream>
int sum(int x, int y); // declaration
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
Why the main function doesn't need the declaration, as other functions like sum need?
A definition of a function is also a declaration of a function.
The purpose of a declaring a function is to make it known to the compiler. Declaring a function without defining it allows a function to be used in places where it is inconvenient to define it. For example:
If a function is used in a source file (A) other than the one it is defined in (B), we need to declare it in A (usually via a header that A includes, such as B.h).
If two or more functions may call each other, then we cannot define all those functions before the others—one of them has to be first. So declarations can be provided first, with definitions coming afterward.
Many people prefer to put “higher level” routines earlier in a source file and subroutines later. Since those “higher level” routines call various subroutines, the subroutines must be declared earlier.
In C++, a user program never calls main, so it never needs a declaration before the definition. (Note that you could provide one if you wished. There is nothing special about a declaration of main in this regard.) In C, a program can call main. In that case, it does require that a declaration be visible before the call.
Note that main does need to be known to the code that calls it. This is special code in what is typically called the C++ runtime startup code. The linker includes that code for you automatically when you are linking a C++ program with the appropriate linker options. Whatever language that code is written in, it has whatever declaration of main it needs in order to call it properly.
I was taught that functions need declarations to be called.
Indeed. A function must be declared before it can be called.
why we don't add a declaration for the main function?
Well, you didn't call main function. In fact, you must not call main at all1, so there is never a need to declare main before anything.
Technically though, all definitions are also declarations, so your definition of main also declares main.
Footnote 1: The C++ standard says it's undefined behaviour to call main from within the program.
This allows C++ implementations to put special run-once startup code at the top of main, if they aren't able to have it run earlier from hooks in the startup code that normally calls main. Some real implementations do in fact do this, e.g. calling a fast-math function that sets some FPU flags like denormals-are-zero.
On a hypothetical implementation, calling main could result in fun things like re-running constructors for all static variables, re-initializing the data structures used by new/delete to keep track of allocations, or other total breakage of your program. Or it might not cause any problem at all. Undefined behaviour doesn't mean it has to fail on every implementation.
The prototype is required if you want to call the function, but it's not yet available, like sum in your case.
You must not call main yourself, so there is no need to have a prototype. It's even a bad a idea to write a prototype.
No, the compiler does not need a forward declaration for main().
main() is a special function in C++.
Some important things to remember about main() are:
The linker requires that one and only one main() function exist when creating an executable program.
The compiler expects a main() function in one of the following two forms:
int main () { /* body */ }
int main (int argc, char *argv[]) { /* body */ }
where body is zero or more statements
An additional acceptable form is implementation specific and provides a list of the environment variables at the time the function is called:
int main (int argc, char* argv[], char *envp[]) { /* body */ }
The coder must provide the 'definition' of main using one of these acceptable forms, but the coder does not need to provide a declaration. The coded definiton is accepted by the compiler as the declaration of main().
If no return statement is provided, the compiler will provide a return 0; as the last statement in the function body.
As an aside, there is sometimes confusion about whether a C++ program can make a call to main(). This is not recommended. The C++17 draft states that main() "shall not be used within a program." In other words, cannot be called from within a program. See e.g. Working Draft Standard for C++ Programming Language, dated "2017-03-21", Paragraph 6.6.1.3, page 66. I realize that some compilers support this (including mine), but the next version of the compiler could modify or remove that behavior as the standard uses the term "shall not".
It is illegal to call main from inside your program. That means the only thing that is going to call it is the runtime and the compiler/linker can handle setting that up.This means you do not need a prototype for main.
A definition of a function also implicitly declares it. If you need to reference a function before it is defined you need to declare it before you use it.
So writing the following is also valid:
int sum(int x, int y) {
return x + y;
}
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
If you use a declaration in one file to make a function known to the compiler before it is defined, then its definition has to be known at linking time:
main.cpp
int sum(int x, int y);
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
sum.cpp
int sum(int x, int y) {
return x + y;
}
Or sum could have its origin in a library, so you do not even compile it yourself.
The main function is not used/referenced in your code anywhere, so there is no need to add the declaration of main anywhere.
Before and after your main function the c++ library might execute some init and cleanup steps, and will call your main function. If that part of the library would be represented as c++ code then it would contain a declaration of int main() so that that it could be compiled. That code could look like this:
int main();
int __main() {
__startup_runtime();
main();
__cleanup_runtime();
}
But then you again have the same problem with __main so at some point there is no c++ anymore and a certain function (main) just represents the entry point of your code.
Nope. You can't call it anyway.
You only need forward declarations for functions called before they are defined. You need external declarations (which look exactly like forward declarations on purpose) for functions defined in other files.
But you can't call main in C++ so you don't need one. This is because the C++ compiler is allowed to modify main to do global initialization.
[I looked at crt0.c and it does have a declaration for main but that's neither here nor there].
Think about this code in C/C++:
bool cond = true;
while(cond){
std::cout << "cond is currently true!";
}
Is it possible to create a function that can be called like this?
myFunction(some_parameters_here){
//Code to execute, maybe use it for callbacks
myOtherFunction();
anotherFunction();
}
I know you can use function pointers and lambda functions, but I was wondering if you can. I'm pretty sure there is a way to do so, because how would while() exist?
while(condition) { expression } is not a function but a control structure / a separate language construct; it executes expression again and again as long as condition evaluates to true (i.e. something != 0).
an function definition of the form void myFunction(int someParameter) { expression }, in contrast, is executed only when it is called by another function.
Hope it helps a bit;
Caution: this solution comes without the guarantee that your code reviewer will like it.
We can use a trick similar to the one Alexandrescu uses for his SCOPE_EXIT macro (awesome one-hour conference, this bit is at 18:00).
The gist of it: a clever macro and a dismembered lambda.
namespace myFunction_detail {
struct Header {
// Data from the construct's header
};
template <class F>
void operator * (Header &&header, F &&body) {
// Do something with the header and the body
}
}
#define myPrefix_myFunction(a, b, c) \
myFunction_detail::Header{a, b, c} * [&]
Using it as follows:
myPrefix_myFunction(foo, bar, baz) {
}; // Yes, we need the semicolon because the whole thing is a single statement :/
... reconstitutes a complete lambda after macro expansion, and lands into myFunction_detail::operator* with acess to foo, bar, baz, and the body of the construct.
This question already has answers here:
What would be a proper invalid value for a pointer?
(7 answers)
Closed 7 years ago.
I'd like to have a function with an optional parameter but without overloading the function. The reason I don't want to overload is because the function body is quite long, and the version with the optional parameter just differs by a single line.
void myFunction(MyClass my_optional_arg = MyClass())
{
// lots of statements
if (optional_argument_was_passed)
doSomething(my_optional_arg);
// lots more statements
}
int main()
{
myFunction();
MyClass my_optional_object();
myFunction(my_optional_object);
}
The problem that I have with the default parameter route is that I don't know how to check whether the optional parameter was passed or not, i.e., I don't know how to set the boolean flag optional_argument_was_passed. For example, just testing equality of the parameter with the default isn't sufficient because that same default value could be passed into the function. What I'd really like is something like this:
void myFunction(MyClass my_optional_arg = some_unique_null_value)
{
// lots of statements
if (my_optional_arg != some_unique_null_value)
doSomething(my_optional_arg);
// lots more statements
}
It has been suggested that I do something like this:
void myFunction()
{
MyClass my_object();
myFunction(my_object);
}
However, this is not quite what I need; the myFunction(MyClass) function is not necessarily the ultimate function to be used. If I call the function without the optional argument, myFunction(), then I don't want any object of class MyClass to even enter the function at all; rather, the statement that uses this object, called doSomething(MyClass) above, should be omitted.
It has also been suggested that I remove the common parts of both functions to its own function myFunction() and then create an overloaded wrapper function to call the statements with the optional parameter:
void myFunction(MyClass my_optional_arg)
{
doSomething(my_optional_arg);
myFunction();
}
This is a solution, but it would be a bit messy because I have a lot of statements before AND after the doSomething(MyClass) call, so I'd need to split the function into several parts:
void myFunction(MyClass my_optional_arg)
{
myFunctionPartA();
doSomething(my_optional_arg);
myFunctionPartB();
}
void myFunctionPartA()
{
// lots of statements
}
void myFunctionPartB()
{
// lots more statements
}
if the functions are similar then call one from the other. OR have an internal 'do all the work and take all the paramters' function that all the overloads call. This is a very common tactic
void Func() // func with foo defaulting to 42
{
Func(42);
}
void Func(int foo)
{
// one million lines of code
}
Stanley Lippman's "C++ primer" mentioned, in page 234 that
Ordinarily, it is a bad idea to declare a function locally. However,
to explain how scope interacts with overloading, we will violate this
practice and use local function declarations.
...
void print(const string &);
void print(double); // overloads the print function
void fooBar(int ival)
{ ...
// bad practice: usually it's a bad idea to declare functions at local scope
void print(int); // new scope: hides previous instances of print
print(ival); // ok: print(int) is visible
print(3.14); // ok: calls print(int); print(double) is hidden
}
Nevertheless, which situation it might make sense to do so, declaring a function inside the body of a function?
I recall similar code in Scheme:
(define (PowerSet set)
(if (null? set) '(())
(let ((PowerSetAfterHead (PowerSet (cdr set) ) ))
(append PowerSetAfterHead
(PowerSet (cdr set) )
(map
(lambda (subset)
(cons (car set) subset
)
)
(PowerSet (cdr set) )
)
)
)
)
)
Is it normally used to hide from misuse of a "local function" that intends for the outer function's usage only? something like internal class? Or is it useful in some design patterns?
The problem arises when there is an ambiguity in calling a function. Thus to avoid the ambiguity in some scope you can redeclare the required function that hides all other functions with the same name of the outer scope.
Consider the following simple example. If you run the following program
#include <iostream>
void f( int ) { std::cout << "f( int )" << std::endl; }
void f( double ) { std::cout << "f( double )" << std::endl; }
int main()
{
f( 10l );
return 0;
}
you will get an error like
prog.cpp:10:9: error: call of overloaded 'f(long int)' is ambiguous f( 10l );
But if you will add a declaration of function f within main like this
#include <iostream>
void f( int ) { std::cout << "f( int )" << std::endl; }
void f( double ) { std::cout << "f( double )" << std::endl; }
int main()
{
void f( double );
f( 10l );
return 0;
}
the code will be compiled and the output will look like
f( double )
Your scheme example both declares and defines a local function.
The C++ example just declares a function locally.
These are different things.
You can create the rough equivalent of scheme local functions with lambdas in C++11.
The declaring of a function locally just says "there exist a function of this name and signature". What more, it does so in a narrower scope than the one outside the function, and as there are functions in said narrower scope only they are considered for overloading (not the ones in the wider scope).
No new function is created -- it must be defined elsewhere. (You cannot define a local function in C++, barring things like local class methods and lambdas)
You could use this to change how overload resolution works, but this is rarely a good idea. In the case that you have an overload ambiguity, you are better off manually converting the types and then calling the overload set, and have it resolve normally.
An alternative is to declare only the overload you want to invoke, then invoke it. This can result in surprising behavior, so do so only in a very narrow scope if you can, and document why you are doing it and what possible problems could occur (as few programmers will have the scope-hiding overload rules at the front of their brain when reading your code without at least a bit of prompting).
I do not think I have ever ran into a situation where I had to declare a function locally.
The handful of times I did it it was because I was hacking into some serious ball of mud code, and wanted to make an extremely local change for prototype/debugging purposes. I simply declared a function signature and called it somewhere. The function was a static local in another .cpp file in the same library elsewhere, I removed the static there and tested the result of calling it.
This saved creating a header file (or modifying one), exposing it formally, including said header where we where using it. Prior to committing to production I would go through steps like that (and probably clean up the interface of that static local function while I was at it).
So, I used it for a quick and dirty prototype hack. The last time I did this I ended up reverting it after I did the prototype hack, which was easier because I had only touched 2 files each at 1 spot.
I was just experimenting with C++. I was trying to write a small macro so that all the functions that I define are automatically stored in a map so that I can query, at run time, what functions exist and run them too. The code is as follows:
#include <map>
using namespace std;
typedef void (*funcPointer)();
map <char*, funcPointer> funcList;
#define Function(x) void x() { funcList[#x] = x;
#define End }
I was used funcPointer and End only for easy readability and implementation. Now, I can define a function as
Function(helloWorld)
cout << "Hello World";
End
Now, to read the function names as a list and run all the functions, I use the following code:
int main() {
//helloWorld();
for (map<char*, funcPointer>::iterator I = funcList.begin(); I != funcList.end(); I++) {
printf(I->first);
I->second();
}
getchar();
return 0;
}
The problem is, if I keep the first line of main() (helloWorld();) commented, the compiler doesn't compile the function and skips it for optimization, as according to the compiler, it is never used. So, the function list turns up empty. If, instead, I call the function once, every thing works perfectly, except that it prints "Hello World" twice. Also, I wrote the macro specifically so I do not have to do that.
So, is there any way that I can force the compiler to compile a function even if it is not used?
The problem is that the code to register the function is inside the function, so won't happen unless you call the function. You might instead register it by initialising a global variable, which will happen automatically before main begins. This might look something like
struct funcRegistration {
funcRegistration(char * name, funcPointer func) {funcList[name] = func;}
};
#define Function(x) \
void x(); \
funcRegistration x##_registration(#x, x); \
void x() {
The compiler compiles the function, however your map won't be populated unless its called.
Because funcList[#x] = x; comes inside the function block { } after macro expansion.