Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C what does [foo] = bar mean?

Tags:

c

I was just reading some code in the st terminal emulator and came across this syntax:

static void (*handler[LASTEvent])(XEvent *) = {
    [KeyPress] = kpress,
    [ClientMessage] = cmessage,
    /* Removed some lines for brevity ... */
};

I have never seen this syntax in C and I am not even sure what to google for. I have a rough idea what it does (defining handler as an array of function pointers), but I would like to understand this syntax better. It seems to be valid at least in C99, but I am looking for some more details why this is correct, how exactly it works and maybe a pointer to the C standard where this syntax is defined.

like image 814
lanoxx Avatar asked Oct 12 '15 17:10

lanoxx


People also ask

What is foo and bar in C?

The terms foobar (/ˈfuːbɑːr/), foo, bar, baz, and others are used as metasyntactic variables and placeholder names in computer programming or computer-related documentation.

What is foo in C programming?

Foo (pronounced FOO) is a term used by programmers as a placeholder for a value that can change, depending on conditions or on information passed to the program. Foo and other words like it are formally known as metasyntactic variables.

What does foo stand for?

Foo is an intentionally meaningless placeholder word often used in computer programming.

Why do developers use foo bar?

Foo is a metasyntactic variable that is commonly used as a placeholder to name variables or code elements. It can be used as the name of a variable, particularly when a programmer wishes to assign a name but doesn't know what name to assign.


1 Answers

This is initializing an array of function pointers with enum indexes. See here.

As mentioned in the comments below uses Designated Initializers.

This short example should show how it can be used.

enum indexes {ZERO, ONE, TWO, FOUR=4};
int array[5] = {[FOUR]=1, [TWO]=9};

for(int i = 0; i < 5; i++)
    printf("%d, ", array[i]);

This prints out

0, 0, 9, 0, 1,
like image 136
jayant Avatar answered Sep 19 '22 08:09

jayant