Here is one not-so-common way of initializing the array:
int a[3] = {[2] 5, [0] 10, [1] 15};
Used this array in the program,
#include <stdio.h>
int main() {
//code
int a[3] = {[2] 5, [0] 10, [1] 15};
printf("a[0] = %d a[1] = %d a[2] = %d\n", a[0], a[1], a[2]);
return 0;
}
Output:
a[0] = 10 a[1] = 15 a[2] = 5
Online Compiler Link: http://code.geeksforgeeks.org/4onQAI
So, I have a question:
Is it the correct way to initialize array?
Close. The correct way is as follows:
int a[3] = {[2] = 5, [0] = 10, [1] = 15};
This is a designated initializer, which allows you to initialize specified elements. Any elements not specified are set to 0.
This is specified in section 6.7.9 of the C standard.
The syntax you show is a non-standard extension supported by some compilers, specifically GCC. If you were to compile with -pedantic
, you would get the following warning:
warning: obsolete use of designated initializer without ‘=’
Your code snippet uses an obsolete syntax for this designated initializer:
int a[3] = {[2] = 5, [0] = 10, [1] = 15};
An alternative syntax for this that has been obsolete since GCC 2.5 but GCC still accepts is to write ‘[index]’ before the element value, with no ‘=’. (reference)
Omitting =
is not standard, and should not be used for new development.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With