Short hand array notation in C/C++


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.

Updated on: 30-Jul-2019

287 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements