简体   繁体   English

任何人都可以解释 C 程序的 output 吗?

[英]Can anyone please explain the output of C program?

I found this problem in a book.我在一本书中发现了这个问题。

Problem:问题:

What is the output of the following program?以下程序的output是什么?

#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));
}

This code, when run, prints out 1.此代码在运行时打印出 1。

I tried understanding it but no it is of no use.我试着理解它,但没有,它没有用。 What is going in this program and why does it output 1?这个程序是怎么回事,为什么 output 1?

Thanks in advance.提前致谢。

proc is indirectly calling fun via a function pointer. proc通过 function 指针间接调用fun The arguments that fun receives are again 6 and 6 , and the equality operator evaluates to an int with the value 1 because they are equal. fun接收到的 arguments 又是66 ,相等运算符的计算结果为值为1int ,因为它们相等。 If they were not equal, the == operator would yield 0 .如果它们不相等,则==运算符将产生0

In main the first line在 main 第一行

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

is calling proc which is taking argument a function pointer and two integer values.正在调用 proc,它采用参数 function 指针和两个 integer 值。 Function pointer pf is defined as typedef int(*pf) (int,int); Function 指针 pf 定义为typedef int(*pf) (int,int); This line printf("%d\n",proc(fun,6,6));这一行printf("%d\n",proc(fun,6,6)); will call the function defined as:将调用 function 定义为:

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

Now in this function pf holds the pointer to function fun.现在在这个 function pf 中持有指向 function fun 的指针。 This will cause the function fun to be called which is returning whether the values of a and b are true or not.这将导致调用 function 函数,它返回 a 和 b 的值是否为真。 Since you have passed 6,6 as the arguments the result will be true and that is why you are getting as 1 as an Answer.由于您已经通过 6,6 作为 arguments 结果将为真,这就是为什么您得到 1 作为答案的原因。

int fun(int,int); 

function takes 2 int arguments and returns an int function 接受 2 个 int arguments 并返回一个 int

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

pf is a function pointer that store the address of address of a function which takes two ints as its agrs and returns an int pf 是一个 function 指针,它存储一个 function 的地址的地址,它以两个 int 作为它的 ags 并返回一个 int

int proc(pf,int,int); 

proc is a function which takes 3 args first is a function pointer to a function like above and two integer args. proc 是一个 function,它接受 3 个参数,首先是一个 function 指针,指向上面的 function 和两个 integer 参数。

proc(fun,6,6);

above statement calls fun with two args 6 and 6 and returns true if they are equal which is how the result is 1上面的语句用两个参数 6 和 6 调用 fun,如果它们相等则返回 true,结果是 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM