为什么打印函数名称会返回值? [英] Why does printing a function name returns a value?

查看:81
本文介绍了为什么打印函数名称会返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不小心打印了一个没有括号的函数名,并打印了一个值.我只是好奇这是怎么发生的?无论函数名称或定义如何,每次运行时输出都是相同的.

I accidentally printed a function name without the parenthesis and it printed a value. I am just curious about how this happens? Output is same irrespective of the function name or definition, and for every time I run it.

答案使我对所有正在阅读此书的人都感到疑惑-将函数名称显式转换为int作品,即int k =(int)foo;

The answers cleared my doubt, to anyone else who is reading this - Explicitly converting the function name to int works, i.e int k=(int)foo;

此测试代码将使事情更加清楚:

This test code will make things more clear:

#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;

void foo(){cout<<'Á';}      //FUNCTION IS NEVER CALLED

int main()
{
    while(_kbhit())         //JUST TO MAKE SURE BUFFER IS CLEARED
    {   getch();}           //SAME RESULT WITHOUT THESE TWO STATEMENTS

    cout<<foo;              //OUTPUT 1
    printf("\n%u", foo);    //OUTPUT 4199232
    /*int k=foo;            //CANNOT CONVERT VOID(*)() TO 'INT'*/
    return 0;
}

推荐答案

对不带括号的函数名称的引用将被解释为函数指针.指针由%u 格式说明符解释为 unsigned int ,这是未定义的行为,但碰巧在大多数系统上都可以使用.

A mention of a function name without parentheses is interpreted as a function pointer. The pointer is interpreted as an unsigned int by the %u format specifier, which is undefined behaviour but happens to work on most systems.

int k = foo 不起作用的原因是,函数指针通常需要强制转换才能转换为 int .但是, printf 宽容得多,因为它使用 varargs 来解析其参数字符串.假定参数的类型与格式字符串中请求的类型匹配.

The reason int k = foo doesn't work is that a function pointer normally needs a cast to be converted to int. However, printf is much more lenient because it uses varargs to parse its argument string; the type of the arguments is assumed to match the type requested in the format string.

这篇关于为什么打印函数名称会返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆