【问题标题】:C Function ExplanationC函数说明
【发布时间】:2014-09-24 17:46:32
【问题描述】:

谁能给我解释一下这个函数的语法?其中 SYS_fork 是一些常量,而 sys_fork 是一个函数。

static int (*syscalls[])(void) = {
[SYS_fork]    sys_fork,
[SYS_exit]    sys_exit,
[SYS_wait]    sys_wait,
[SYS_pipe]    sys_pipe,
[SYS_read]    sys_read,
[SYS_kill]    sys_kill,
[SYS_exec]    sys_exec,
};

谢谢!

【问题讨论】:

  • 很确定这需要更多的上下文。

标签: c xv6


【解决方案1】:

您刚刚遇到了designated initializers 的用法。它们存在于 C99 中,也可作为 GCC 扩展提供,广泛用于 Linux 内核代码(以及其他)。

来自文档:

在 ISO C99 中,您可以按任何顺序给出 [数组] 的元素,指定它们适用的数组索引或结构字段名称,GNU C 也允许这作为 C90 模式的扩展。 [...]

要指定数组索引,请在元素值之前写上'[index] ='。例如,

int a[6] = { [4] = 29, [2] = 15 };

相当于:

int a[6] = { 0, 0, 15, 0, 29, 0 };

[...]

自 GCC 2.5 以来已过时但 GCC 仍然接受的另一种语法是在元素值之前写“[index]”,不带“=”。

用简单的英语,syscalls is a static array of pointer to function taking void and returning int。数组索引是常量,它们的关联值是相应的函数地址。

【讨论】:

  • 根据该描述发布的代码难道不需要=s 标志吗?
  • @dolan :您能解释一下 SYS_fork、SYS_exit .....values 是如何充当索引的吗? :-)
  • @Abhishek 它们可能在代码的其他地方定义。例如作为枚举:enum { SYS_fork, SYS_exit, ... };。这会创建一组标识符,它们的行为类似于可以用作索引的常量 (0, 1, ...)。它们也有可能被定义为宏。
  • @dolan 从您发布的链接中:“自 GCC 2.5 以来已过时但 GCC 仍然接受的另一种语法是在元素值之前写入 [index],没有 =。 "
  • @milleniumbug 究竟什么是过时的?它自己的机械师还是带有(out)=的机械师?
【解决方案2】:

运行以下代码,您将知道发生了什么:

#include <stdio.h>

void function_1(char *); 
void function_2(char *);
void function_3(char *);
void function_4(char *);

#define func_1    1
#define func_2    2
#define func_3    3
#define func_4    4

void (*functab[])(char *) = {       // pay attention to the order
    [func_2] function_2,
    [func_3] function_3,
    [func_1] function_1,
    [func_4] function_4
};

int main()
{
    int n;

    printf("%s","Which of the three functions do you want call (1,2, 3 or 4)?\n");

    scanf("%d", &n);

    // The following two calling methods have the same result

    (*functab[n]) ("print 'Hello, world'");  // call function by way of the function name of function_n

    functab[n] ("print 'Hello, world'");   // call function by way of the function pointer which point to function_n

    return 0;
}

void function_1( char *s) { printf("function_1 %s\n", s); }

void function_2( char *s) { printf("function_2 %s\n", s); }

void function_3( char *s) { printf("function_3 %s\n", s); }

void function_4( char *s) { printf("function_4 %s\n", s); }

结果:

Which of the three functions do you want call (1,2, 3 or 4)?
1
function_1 print 'Hello, world'
function_1 print 'Hello, world'

 Which of the three functions do you want call (1,2, 3 or 4)?
 2
 function_2 print 'Hello, world'
 function_2 print 'Hello, world'

 Which of the three functions do you want call (1,2, 3 or 4)?
 3
 function_3 print 'Hello, world'
 function_3 print 'Hello, world'

 Which of the three functions do you want call (1,2, 3 or 4)?
 4
 function_4 print 'Hello, world'
 function_4 print 'Hello, world'

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2016-05-17
    • 2014-04-06
    • 2013-12-23
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2012-09-09
    相关资源
    最近更新 更多