Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
A shorthand array notation in C for repeated values?
An array stores multiple values of the same data type. Sometimes you need to initialize several array elements with the same value, such as setting multiple positions to 3, 3, 3, 3. C provides a shorthand notation called designated initializers to simplify this process and reduce code repetition.
Syntax
[startIndex ... endIndex] value
Where startIndex and endIndex define the range of positions to initialize with the specified value.
Example: Array Initialization with Repeated Values
This example demonstrates how to use the shorthand notation to initialize array elements with repeated values −
#include <stdio.h>
int main() {
int array[10] = {[0 ... 4]3, [6 ... 9]5};
printf("Array elements: ");
for (int i = 0; i < 10; i++) {
printf("%d ", array[i]);
}
printf("<br>");
return 0;
}
Array elements: 3 3 3 3 3 0 5 5 5 5
How It Works
-
[0 ... 4]3initializes positions 0 through 4 with value 3 -
[6 ... 9]5initializes positions 6 through 9 with value 5 - Position 5 remains uninitialized (defaults to 0 for global/static arrays)
Key Points
- This notation is a GCC extension, not part of standard C
- Unspecified elements are automatically initialized to zero
- You can combine regular initialization with range initialization
- The range is inclusive on both ends
Conclusion
The designated initializer syntax [start ... end]value provides a convenient way to initialize array ranges with repeated values. While it's a GCC extension, it significantly reduces code when dealing with large arrays that need repeated initialization patterns.
