Home > Blockchain >  What does "type name[size]" mean in a function argument?
What does "type name[size]" mean in a function argument?

Time:09-17

I was analyzing the SKIA source code and found this:

constexpr unsigned kMaxBytesInUTF8Sequence = 4;
// ...
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I know (pardon me if I'm wrong) that char utf8[kMaxBytesInUTF8Sequence] decays to char*, as also would char utf8[] or just char* utf8.

Therefore, I think it wouldn't make sense to write it that way, right?

CodePudding user response:

A function parameter having an array type is adjusted by the compiler to pointer to the array element type.

Thus these function declarations

SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[10] = nullptr);
SK_SPI size_t ToUTF8(SkUnichar uni, char *utf8 = nullptr);

declare the same one function.

This parameter declaration

char utf8[kMaxBytesInUTF8Sequence]

is used for self-docimentation specifying that the passed array must have no greater than kMaxBytesInUTF8Sequence elements or the user can pass a null pointer.

CodePudding user response:

In a function parameter, array notation is just syntax sugar. The size specified inside the brackets is ignored, and the actual parameter type is just a pointer.

In other words, this declaration:

constexpr unsigned kMaxBytesInUTF8Sequence = 4;
// ...
SK_SPI size_t ToUTF8(SkUnichar uni, char utf8[kMaxBytesInUTF8Sequence] = nullptr);

Is treated by the compiler as this:

constexpr unsigned kMaxBytesInUTF8Sequence = 4;
// ...
SK_SPI size_t ToUTF8(SkUnichar uni, char* utf8 = nullptr);

However, specifying the parameter declaration in array notation acts as documentation to programmers that the function expects a char[] array of size at least kMaxBytesInUTF8Sequence to be passed in. But there is nothing the compiler does to actually validate that.

  • Related