Difference between `a` and `&a` in C++ where `a` is an array

前端 未结 3 1889
一向
一向 2021-02-04 17:00

I am confused about the output of the following code.

#include
#include
using namespace std;
int main()
{
  int a[] = {1,2,3};
           


        
3条回答
  •  走了就别回头了
    2021-02-04 17:34

    In C, the expression a is a primary expression which designates an array object. In a context where this expression is evaluated, it produces a value which is of pointer type, and points to the first element of the array.

    This is a special evaluation rule for arrays. It does not mean that a is a pointer. It isn't; a is an array object.

    When the sizeof of & operators are applied to a, it is not evaluated. sizeof produces the size of the array, and & takes its address: it produces a pointer to the array as a whole.

    The values of the expressions a and &a point to the same location, but have a different type: a pointer to type of the array element (such as pointer to int), versus the type of the array (such pointer to array of 10 int) respectively.

    C++ works very similarly in this area for compatibility with C.

    There are other situations in C where the value of an expression which denotes a value or object of one type produces a value of another type. If c has type char, then the value of c is a value of type int. Yet &c has type char *, and sizeof c produces 1. Just like an array is not a pointer, c is not an int; it just produces one.

    C++ isn't compatible in this area; character expressions like names of char variables or character constants like 'x' have type char. This allows void foo(int) and void foo(char) to be different overloads of a function foo. foo(3) will call the first one, and foo('x') the second.

提交回复
热议问题