C++ * vs [] as a function parameter

后端 未结 3 442
醉酒成梦
醉酒成梦 2021-01-18 11:11

What is the difference between:

void foo(item* list)
{
    cout << list[xxx].string;
}

and

void this(item list[])
{
          


        
相关标签:
3条回答
  • 2021-01-18 12:02

    To the compiler, there is no difference.

    It reads different though. [] suggests you want to pass an array to the function, whereas * could also mean just a simple pointer.

    Note that arrays decay to pointers when passed as parameters (in case you didn't already know).

    0 讨论(0)
  • 2021-01-18 12:02

    FYI:

    void foo(int (&a)[5]) // only arrays of 5 int's are allowed
    {
    }
    
    int main()
    {
      int arr[5];
      foo(arr);   // OK
    
      int arr6[6];
      foo(arr6); // compile error
    }
    

    but foo(int* arr), foo(int arr[]) and foo(int arr[100]) are all equivalent

    0 讨论(0)
  • 2021-01-18 12:05

    They are the same - completely synonymous. And the second is item list[], not item[]list.

    However it is customary to use [] when the parameter is used like an array and * when it's used like a pointer.

    0 讨论(0)
提交回复
热议问题