2012-04-05 58 views
0

我在一本书中发现了这个问题。任何人都可以请解释C程序的输出?

问题:

以下程序的输出是什么?

#include <stdio.h> 
int fun(int,int); 
typedef int(*pf) (int,int); 
int proc(pf,int,int); 

int main() 
{ 
    printf("%d\n",proc(fun,6,6)); 
    return 0; 
} 

int fun(int a,int b){ 
    return (a==b); 
} 

int proc(pf p,int a,int b){ 
    return ((*p)(a,b)); 
} 

此代码在运行时,打印出1

我试图理解它,但没有它是没有用的。这个程序中发生了什么,为什么它输出1?

在此先感谢。

+8

这看起来像功课,我 – Petesh 2012-04-05 08:55:43

+0

的答案是:'0'! – leppie 2012-04-05 09:14:30

回答

2

proc经由函数指针间接调用fun。该fun接收的参数是再次66和平等的运营商计算结果为int与价值1,因为他们是平等的。如果不相等,则==运营商将产生0

+0

感谢您的帮助。 – 2012-04-05 09:35:37

1

在主第一行

printf("%d\n",proc(fun,6,6)); 

是主叫PROC其采取自变量的函数指针和两个整数值。函数指针PF被定义为typedef int(*pf) (int,int); 此行printf("%d\n",proc(fun,6,6));将调用定义为函数:

int proc(pf p,int a,int b){ 
return ((*p)(a,b)); 
} 

在现在这个功能PF持有指针函数fun。这将导致函数fun被调用,返回a和b的值是否为真。既然你已经通过6,6作为参数,结果将是真实的,这就是为什么你得到1作为答案。

0
int fun(int,int); 

函数采用2个INT参数并返回一个int

typedef int(*pf) (int,int); 

PF是存储这需要两个整数作为其AGRS一个函数的地址的地址的函数指针并返回一个int

int proc(pf,int,int); 

PROC是一个函数,它接受3个ARGS第一个是一个函数指针的功能类似于上面和两个整数ARGS。

proc(fun,6,6); 

上述语句调用乐趣有两个参数6,6,如果它们相等返回true这是今天的结果如何1

相关问题