What do square brackets mean in array initialization in C?

后端 未结 4 675
你的背包
你的背包 2020-11-30 23:14
static uint8_t togglecode[256] = {
    [0x3A] CAPSLOCK,
    [0x45] NUMLOCK,
    [0x46] SCROLLLOCK
};

What\'s the meaning of [0x3A] her

相关标签:
4条回答
  • 2020-11-30 23:47

    According to the GCC docs this is ISO C99 compliant. They refer to it as "Designated Initialzers":

    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 };
    

    I've never seen this syntax before, but I just compiled it with gcc 4.4.5, with -Wall. It compiled successfully and gave no warnings.

    As you can see from that example, it allows you to initialize specific array elements, leaving the others untouched.

    0 讨论(0)
  • 2020-12-01 00:03

    It means initialise the n-th element of the array. The example you've given will mean that:

    togglecode[0x3A] == CAPSLOCK
    togglecode[0x45] == NUMLOCK
    togglecode[0x46] == SCROLLLOCK
    

    These are called "designated initializers", and are actually part of the C99 standard. However, the syntax without the = is not. From that page:

    An alternative syntax for this which has been obsolete since GCC 2.5 but GCC still accepts is to write [index] before the element value, with no =.

    0 讨论(0)
  • 2020-12-01 00:04

    It's (close to) the syntax of designated initializers, a C99 feature.

    Basically, it initializes parts of an array, for example;

    int aa[4] = { [2] = 3, [1] = 6 };
    

    Intializes the second value of the array to 6, and the third to 3.

    In your case the array offsets happen to be in hex (0x3a) which initializes the 58'th element of the array to the value of CAPSLOCK which presumably is defined in the code above the code you're showing.

    The version in your code without the = seems to be a gcc specific extension.

    0 讨论(0)
  • 2020-12-01 00:11

    That was introduced in C99 and it's called a designated initialiser.

    It basically allows you to set specific values in an array with the rest left as defaults.

    In this particular case, the array indexes are the keyboard scan codes. 0x3a is the scan code in set #1 (see section 10.6) for the CapsLock key, 0x45 is NumLock and 0x46 is ScrollLock.

    On the first link above, it states that:

    int a[6] = { [4] = 29, [2] = 15 };
    

    is equivalent to:

    int a[6] = { 0, 0, 15, 0, 29, 0 };
    

    Interestingly enough, though the link states that = is necessary, that doesn't appear to be the case here.

    0 讨论(0)
提交回复
热议问题