SWIIWII SWIIWII - 3 months ago 9
C Question

Assign an array of int (only one element) to an integer in c

I've seen on a web page that we could do this:

int k = {5};


When I try it myself I found that this works in C programming and the value of
k
is
5
.


  • q1: Why could we assign an array of integer (even if there is only one element) to a variable of integer type, shoudn't there be some errors?

  • q2: What is this type of assignment used for? (in which situation and why we use it or perhaps we won't use it anymore?)


Answer

There isn't an array, C syntax simply permits this. Both of these are equivalent:

int k = 5;
int k = {5};

As seen in the syntax rules for initialization (Quoted from: 6.7.9 Initialization Syntax 1.):

initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }

initializer-list:
    designation opt initializer
    initializer-list , designation opt initializer

initializer is either assignment-expression, which corresponds to:

int k = 5;

or an {initializer-list}, which requires brackets and an initializer-list, which can be an initializer, which can be an assignment-expression:

int k = {5};