Home > Net >  Assigning array to an int in C
Assigning array to an int in C

Time:10-30

I have written the following code in C

int main(){
    int a = {1, 2, 3};
}

It seems like the variable assigned, in this case a, always takes the value of the first array element. Now I'm wondering if the other array elements are discarded, or written to the memory after a, thus causing a buffer overflow.

CodePudding user response:

This declaration

 int a = {1, 2, 3};

is semantically invalid (it breaks the semantic rule referred below). A scalar object may not be initialized by a braced initializer list with more than one initializer.

From the C Standard (6.7.9 Initialization)

11 The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type.

That is the comma in the braced initializer list is considered as a separator of initializers and for a scalar object only a single expression is allowed.

When more than one initializer is present then the compiler assumes that the initialized object is an aggregate.

To declare an array you need to write

 int a[] = {1, 2, 3};

or

 int a[N] = {1, 2, 3};

where N is an integer value equal to or greater than 3.

CodePudding user response:

int a = {1, 2, 3}; is not valid C code.

It is a so-called constraint violation in the C standard, after which a compiler is required to issue a diagnostic message:

C17 6.7.9/2:

Constraints
No initializer shall attempt to provide a value for an object not contained within the entity being initialized.

It's not a syntax error though, we may actually write weird crap such as int a = {1}; with a single, brace-enclosed initializer. The result no matter the error reason is the same though - compilers must issue diagnostic messages for all constraint- and syntax violations.

To avoid wasting your time at trouble-shooting invalid C code such as this, study What compiler options are recommended for beginners learning C?


As for what compilers like gcc and clang do when faced with such non-standard code - they appear to simply discard the superfluous initializers. If I compile this code with gcc/clang for x86 and ignore the diagnostic message:

int foo (void)
{
    int a = {1, 2, 3};
    return a;
}

The resulting x86 assembly is

mov     eax, 1
ret

Which when translated back to C is 100% equivalent to

int foo (void)
{
    return 1;
}

It's important to understand that this is a non-standard compiler extension though, and no guaranteed or portable behavior.

CodePudding user response:

int main(void)
{
  int a[3] = {1, 2, 3};
  printf("%d\n", a[0]);
  return(0);
}
Output : 1
  • Related