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

2020-04-04 05:20发布

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?

3条回答
仙女界的扛把子
2楼-- · 2020-04-04 05:29

It's not usual to use pointer to main() or the address of main() but..

Anyway, it is allowed since, as every function (and any symbol, e.g. variable) it has its own address. And the address of main() may be needed - especially when you write code for embedded systems and you play with dynamic loading of the code or run-time inspection. Or there are a bootloader and actual running firmware.

Often main() is an entry point to the dynamically loaded code (e.g from FLASH to RAM) and thus it is referenced (called directly or assigned to the relevant pointer) in bootloader.

Refer to MicroC-OS/II or VxWorks - both use main() in this way

查看更多
家丑人穷心不美
3楼-- · 2020-04-04 05:37

Since main is not "used" (you're not evaluating it) then it should be legal according the link you supplied.

查看更多
4楼-- · 2020-04-04 05:40

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.

查看更多
登录 后发表回答