What's a modern term for “array/pointer equivalence”?

后端 未结 11 1258
孤城傲影
孤城傲影 2020-12-14 06:12

Just about everyone reading this is probably familiar with these three key facts about C:

  1. When you mention the name of an array in an expression, it evaluates
11条回答
  •  情歌与酒
    2020-12-14 06:29

    1. The "array subscripting" operator [] works just as well for pointers as it does for arrays.

    No, in fact it only works for pointers. Whenever you type [] in an expression, you always get a pointer to the first element. This is guaranteed to happen since arr[i] must be equivalent to *(arr + i). The former is "syntactic sugar" for the latter.

    1. A function parameter that seems to be an array actually declares a pointer.

    This is actually a special case, referred to as "array adjustment", where the compiler implicitly changes the declaration of a function parameter of array type into a pointer to the first element. The rationale is surely to make functions compatible with the "array decay" of expressions, but the C standard keeps the terms separate.

    Both cases, expressions and function parameters, are often referred to informally as "array decay". Though sometimes this is only used for expressions and not for function parameters. I don't think there exists a single, consistent use of the term. "Array decay" is the best one I think, although the C standard does not use that term anywhere.


    (I dislike the term "equivalence", because an array can turn into a pointer, but not the other way around. Indeed there's always countless beginners coming up with confused beliefs such as "arrays and pointers are the same thing". Calling them "equivalent" doesn't exactly help.)

提交回复
热议问题