Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C [x ... y] ranged assignment

Tags:

arrays

c

I came across some code today which used syntax that in my years of doing C programming I've never seen before.

MWE:

#include<stdio.h>

char *example_array[] = {
    [0 ... 5] = "hello world",
    [6 ... 10] = "goodbye world"
};

int main(void) {
    printf("%s, %s.\n", example_array[3], example_array[7]);
    return 0;
}

Expected output:

hello world, goodbye world.

It's pretty clear what's going on here in a static context, but I'm curious if this can be used as a convenient shortcut in non-static shortcuts, such as assignments in a loop. Of course, it wouldn't give any performance boost that -funroll-loops couldn't, but it might make for cleaner code in, say, matrix row assignments or otherwise.

clang and gcc give no warnings by default when using this syntax, but I've never seen it documented anywhere. Is this some kind of extension, or is it standard C syntax?

like image 747
PyroAVR Avatar asked Aug 18 '18 01:08

PyroAVR


1 Answers

This is a GNU extension to designated initializers supported by both gcc and clang, which you can read about in the gcc docs. Note that this is only for initializers, not for assignments, which are very different things, despite both using the = symbol.

like image 187
Chris Dodd Avatar answered Nov 08 '22 03:11

Chris Dodd