Home > Back-end >  can use " int a = {0} " in C programe to init a array?
can use " int a = {0} " in C programe to init a array?

Time:01-10

I found this code , when I compile it , the compiler tell me "subscripted value is neither array nor pointer" . I know my platform is old . but I want know that "unsigned int bValue = {0}" is a new way to init array ?

unsigned int bValue = {0};
uBlockSize = sizeof(bValue) / sizeof(unsigned int);
for (i = 0; i < uBlockSize; i  )
    bValue[i] = ui8Value << 24U |
    ui8Value << 16U |
    ui8Value <<  8U |
    ui8Value;

I want know that "unsigned int bValue = {0}" is a new way to init array ?

CodePudding user response:

You declared a scalar object of the type unsigned int

unsigned int bValue = {0};

That is it is not an array declaration and hence you may not use the subscript operator with the identifier bValue. And the compiler reports about this prohibition.

However you may initialize scalar objects with expressions optionally enclosed in braces.

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 declaration itself is correct. Only it declares not an array but a scalar object.

You could declare an array for example the following way

unsigned int bValue[] = {0};

In this case bValue is an array with one element initialized by 0.

CodePudding user response:

The code doesn't compile (I tested the latest versions of clang, gcc and MSVC) because bValue[i] is not applicable to a scalar. bValue doesn't appear to be an array (maybe the original code looks different?); therefore, any attempt at indexing will result in compilation error.

As correctly pointed out by @nielsen, the initialization in itself is correct, although it's more often seen applied to arrays.

  • Related