Short Hand Array Notation in C/C++



If there are repeated values are present in an array in C, then we can use shorthand array notation to define that array. For example,

int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2};
// This specifies that index 0-3 will be 7
// index 4-5 will be 6
// and index 6-9 will be 2

// This notation is equivalent to
int array[10] = {7, 7, 7, 7, 6, 6, 2, 2, 2, 2};

Example Code

Here is an example code that demonstrates the shorthand array notation in C:

#include <stdio.h> 
int main() { 
    int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2}; 
    // Print the array
    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++ this syntax is not supported.

Updated on: 2025-06-02T19:35:53+05:30

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements