Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Function Explanation

Tags:

c

xv6

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!

like image 771
Rubab Zahra Sarfraz Avatar asked Sep 24 '14 17:09

Rubab Zahra Sarfraz


People also ask

What is function in C explain?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. Functions are used to perform certain actions, and they are important for reusing code: Define the code once, and use it many times.

What is function in C and explain its types?

Every program in C has a function. Even if you do not use a library or user-defined function, you will have to use the main function. The main function is the program's entry point, as that is where the compiler will start executing the code. Even if a function does not return a value, it has a return type.


1 Answers

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.

like image 128
user703016 Avatar answered Oct 05 '22 01:10

user703016