KrohnusMelavea
KrohnusMelavea

Reputation: 33

Does specifying array length when initializing affect compile time?

I understand that at runtime, const char text[] = "some char array" is the same as const char text[16] = "some char array".

Is there any difference in compile time? I reckon there would be, as telling the compiler how many elements there are in the array ought to be faster than it counting the number of elements. I understand that, even if it makes a difference, it will be inconceivably small, but curiosity got the better of me, so I thought I'd ask.

Upvotes: 0

Views: 138

Answers (1)

Emmef
Emmef

Reputation: 522

You should favour readable code that reduces cognitive load over code that might compile faster. Your assumption that something compiles faster could as well be the other way round (see below). You simply do not know the compiler implementation and in general, the difference in compile speeds is negligible.

In the case of a constant string (that you never reassign a value to), I would omit the length, as it adds clutter and the compiler is perfectly able to determine the length it needs.

You can also reason that adding the number is slower. After all, the compiler needs to parse the string and thus knows its length anyway. Adding the 16 in the declaration forces the compiler to also parse a number and check whether the string ain't too long. That might make compilation slower. Who knows? But again: the difference is likely negligible, compared to all the other wonders that compilers do (and quite efficiently). So don't worry about it.

Upvotes: 3

Related Questions