Short hand array notation in C/C++

C++CServer Side ProgrammingProgramming

If there are repeated values are present in C then we use shorthand array notation to define that array.

Here is an example:

Example Code

#include <stdio.h>
int main() {
int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2};
for (int i = 0; i < 10; i++)
printf("%d ", array[i]);
return 0;
}

Output

7 7 7 7 6 6 2 2 2 2

In this program,

int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2}

is similar as,

int array[10] = {7, 7, 7, 7, 6, 6, 2, 2, 2, 2}.

If there is any gap in the middle of the array it will be filled up by 0.

In C++ above program will give the same output but it will give warnings with the output.

Published on 29-Mar-2019 15:30:34