程序的输出? [英] Output of the Program?

查看:109
本文介绍了程序的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

//程序的直接链接: http://codepad.org/fBIPiHGT

// direct link of program : http://codepad.org/fBIPiHGT

推荐答案

程序的输出是:

1

好,让我们看看发生了什么。

Ok, so let's see what's going on there.

#include<stdio.h>

此行只包含标准输入/输出功能。

This line just include standard input/output functionality.

int fun(int, int);

这告诉编译器:好,我们有一个名为 fun 获取两个 int 变量,返回 int

This tells the compiler: Ok, we have a function named fun taking two int variables, returning an int.

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

这将安装一个指向函数的指针的快捷方式,两个 int 变量返回 int ,所以这种函数指针可以使用 pf 缩写。

This installs kinda shortcut for a pointer to a function taking two int variables returning int, so this kind of function pointer can be abbreviated using pf.

int proc(pf, int, int);



告诉编译器:好的,我们有一个名为 proc 获取一个 pf 变量(就像我们上面看到的)一个函数指针指向两个 int 变量返回 int ),两个 int 变量,返回 int

Tells the compiler: Ok, we have a function named proc taking a pf variable (which is - like we saw above - a function pointer to a function taking two int variables returning an int), two int variables, returning an int.

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

程序执行时执行的中央过程。它告诉程序打印一个数字(%d )和换行符( \\\
)。该数字的值应为 proc(fun,6,6)

The central procedure that's run when the program is executed. It tells the program to print a number (%d) and a newline (\n). The number shall have the value of proc(fun,6,6).

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

这里我们有什么函数 fun 应该做。该函数比较 a b ,如果相等则返回1,否则返回0 == 在C)。

Here we have what function fun is supposed to do. This function compares a and b, returns 1 if they're equal, 0 otherwise (just the definition of results of == in C).

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

这里我们有 proc 实际上:它需要一个函数指针(如上所述 - ...) p 和两个int。然后它调用应用于给定的两个参数的给定函数( p )( a

Here we have what proc actually does: It takes a function pointer (which is - as we saw above - ...) p and two ints. Then it calls the given function (p) applied to the two arguments given (a and b) and returns p's result.

因此,如果我们调用 code> proc(fun,6,6) proc 会调用 fun / code>,其计算结果为1(因为 6 == 6 )并返回此结果( 1 )。

So, if we call proc(fun, 6, 6), proc will call fun(6,6), which evaluates to 1 (since 6==6) and returns this result (1).

因此,输出将只是

1

但老实说:请查看一些事情, (为什么是输出这个和那个):

But honestly: Please have a look at some things and try to figure out things yourself before just asking (why is the output this-and-that):

  • http://www.newty.de/fpt/index.html: Function pointers

这篇关于程序的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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