简体   繁体   中英

C [x … y] ranged assignment

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM