7

根据这个答案 ,使用函数 main() 是非法的(第 3.6.1.3 节),如果函数的名称出现在可能评估的表达式中(第 3.2 节) ,则使用该函数。

假设我有这个代码:

printf( "%p", &main );

其中函数的名称main()出现在表达式中&main

上面的代码会是非法的吗?

4

3 回答 3

3

是的。正如您所引用的,标准说您不能使用 main.

还要注意函数的地址匹配"%p"。对应的参数必须有 type void*; 任何其他类型(可能除外char*)都是非法的,并导致未定义的行为。

于 2013-03-20T14:02:40.240 回答
0

由于main未“使用”(您没有对其进行评估),因此根据您提供的链接它应该是合法的。

于 2013-03-20T14:02:23.377 回答
-3

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

于 2013-03-20T14:16:12.860 回答