Search code examples
cxv6

C Function Explanation


Can someone please explain to me the syntax of this function? where SYS_fork is some constant and sys_fork is a function.

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,
};

Thank you!


Solution

  • You've just encountered a use of designated initializers. They exist in C99 and are also available as a GCC extension, widely used in the Linux kernel code (among others).

    From the docs:

    In ISO C99 you can give the elements [of the array] in any order, specifying the array indices or structure field names they apply to, and GNU C allows this as an extension in C90 mode as well. [...]

    To specify an array index, write ‘[index] =’ before the element value. For example,

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

    is equivalent to:

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

    [...]

    An alternative syntax for this that has been obsolete since GCC 2.5 but GCC still accepts is to write ‘[index]’ before the element value, with no ‘=’.

    In plain English, syscalls is a static array of pointer to function taking void and returning int. The array indices are constants and their associated value is the corresponding function address.