From K&R page 99:
As formal parameters in a function definition,
char s[];
and
char *s;
are equivalent; we prefer the latter because it says more explicitly that the variable is a pointer.
I need some clarification as to why "saying more explicitly that the variable is a pointer" would have any importance? I would expect the reason is for the program to be faster rather than more explicit, as stated in page 97:
The pointer version will in general be faster but, at least to the uninitiated, somewhat harder to understand
But in that case, why would the pointer version be faster? if arr[i]
just equivalent to *(a+i)
why would the program be faster? is it because C doesn't need to convert the array to the pointer version?
Outside of a parameter list, char s[]
and char *s
are different.
void foo( void ) {
char a[] = "abcdef"; // An array of 7 `char` elements.
char *p = "abcdef"; // A pointer that points to a sequence of 7 `char` objects.
}
In a parameter list, char s[]
and char *s
are 100% equivalent by definition.
void foo(
char p1[], // A pointer that points to a `char` object.
char *p2 // A pointer that points to a `char` object.
);
It's saying that since s
is a pointer, it's clearer to use char *s
. Using char s[]
, while equivalent, could mislead "the uninitiated" into thinking it's an array when it's not.
Note that not everyone agrees with always using char *s
instead of char s[]
for parameters. I'm just explaining the opinion expressed by the book as requested.
Since char s[]
and char *s
are 100% equivalent in a parameter list, there is no difference in performance.
When talking about performance, I believe the book is referring to code using variable pointers vs code using constant indexed pointers, such as
for (size_t i = 0; i < n; ++i) dst[i] = src[i];
-vs-
for (size_t i = 0; i < n; ++i) *(dst++) = *(src++);
This is just a guess since the book doesn't explain to what it's referring.
I would largely ignore that statement. Even if it was true at the time the book was written, there has been lots of changes to CPUs and compilers since. More importantly, this focus on micro-optimizations is best avoided except when justified.