C [x ... y]范围分配 [英] C [x ... y] ranged assignment

查看:61
本文介绍了C [x ... y]范围分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天遇到了一些代码,这些代码使用的语法在我多年的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;
}

预期输出:

hello world, goodbye world.

很明显,在静态上下文中发生了什么,但是我很好奇它是否可以用作非静态快捷方式中的便捷快捷方式,例如循环中的赋值.当然,它不会提供-funroll-loops无法提供的任何性能提升,但可以使矩阵行分配或其他方式中的代码更简洁.

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.

clanggcc不发出任何警告,但我从未见过任何地方对其进行过记录.这是某种扩展,还是标准的C语法?

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?

推荐答案

这是gcc和clang支持的指定初始化程序的GNU扩展,您可以阅读有关

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.

这篇关于C [x ... y]范围分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆