I understand how arrays decay to pointers. I understand that, for the compiler, this:
void foo(int *arg1);
is 100% equivalent to this:
void foo(int arg1[]);
Should one style be preferred over the other? I want to be consistent, but I'm having a hard time justifying either decision.
Although int main(int argc, char *argv[])
and int main(int argc, char **argv)
are the same, the former seems to be much more common (correct me if I'm wrong).
I would recommend against using the []
syntax for function parameters.
The one argument in favour of using []
is that it implies, in a self-documenting way, that the pointer is expected to point to more than one thing. For example:
void swap(int *x, int *y)
double average(int vals[], int n)
But then why is char *
always used for strings rather than char []
? I'd rather be consistent and always use *
.
Some people like to const
everything they possibly can, including pass-by-value parameters. The syntax for that when using []
(available only in C99) is less intuitive and probably less well-known:
const char *const *const words
vs. const char *const words[const]
Although I do consider that final const
to be overkill, in any case.
Furthermore, the way that arrays decay is not completely intuitive. In particular, it is not applied recursively ( char words[][]
doesn't work). Especially when you start throwing in more indirection, the []
syntax just causes confusion. IMO it is better to always use pointer syntax rather than pretending that an array is passed as an argument.
More information: http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr#aryptrparam .
Except for char*
, I use Type array[N]
, where N is some number or a defined constant, when the passed item conceptually is an array (ie, it contains N>1 elements), Type * pointer
when the passed item is a pointer to exactly one object.
I tend to use std::vector
if the array is of a variable size. C99's concept of variable sized arrays is not available in C++.
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.