简体   繁体   中英

can use " int a = {0} " in C programe to init a array?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM