Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it illegal to take address of main() function?

According to this answer using function main() is illegal (§3.6.1.3) and a function is used if its name appears in a potentially evaluated expression (§3.2).

Suppose I have this code:

printf( "%p", &main );

in which name of function main() appears in expression &main.

Will the code above be illegal?

like image 251
sharptooth Avatar asked Mar 20 '13 13:03

sharptooth


People also ask

What is the address of the main function?

The address is the memory location where the entity is stored. Every block of code in the program has its own memory location in the program. Which means like any variable or object methods and functions also have memory address.

Can you take the address of an rvalue?

2) non-modifiable lvalues, which are const. rvalue — The expression that refers to a disposable temporary object so they can't be manipulated at the place they are created and are soon to be destroyed. An address can not be taken of rvalues. An rvalue has no name as its a temporary value.

Can we call main function inside another function?

Although you can call the main() function within itself and it is called recursion. Recursion is nothing but calling the same function by the function itself.

Can main call itself in C++?

The main() function can call itself in C++. This is an example of recursion as that means a function calling itself.


1 Answers

Yes. As you quote, the standard says that you cannot use main.

Note too that the address of a function does not match "%p". The corresponding argument must have type void*; any other type (except maybe char*) is illegal, and results in undefined behavior.

like image 136
James Kanze Avatar answered Oct 01 '22 13:10

James Kanze