What is the correct input data type for the [] operator?

When accessing the array, we use the [] operator as follows:

 int a[5]; ... a[b] = 12; 

What is the correct data type for variable b above?

I found that a[b] equivalent to *(a + b) , which makes me think that I would like b be void* or size_t , but I'm not sure.

+4
source share
4 answers

One of a and b must be a pointer, and the other must be any integer type. The proof follows.

Since a[b] is identical (*((a)+(b))) for C 2011 (n1570) 6.5.2.1 2, a and b can be any types for which the last expression is defined.

In 6.5.3.2, the 2 operand of the unary operator * must be of type pointer. Therefore, the result (a)+(b) must be of type pointer.

In 6.5.6, the binary + operator accepts various combinations of types, but the only one that gives the type of a pointer is a combination of a pointer and an integer, as described in 6.5.6 8.

According to 6.5.6 8, an integer can be added to the pointer, and the result is of the operand type of the pointer. In clause 6.5.6, no distinction is made about the order of operands + , so they can be in any order. Thus, any of a and b can be a pointer, and the other an integer.

+4
source

From C standard ( ISO / IEC 9899: TC2 ) Sec 6.5.2.1 Array-based signature

A postfix expression followed by an expression in square brackets [] is the indexed designation of an element of an array object. The definition of the index operator [] that E1[E2] coincides with (*((E1)+(E2))) . Due to the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the starting element of an array object) and E2 is an integer , E1[E2] denotes the E2-th element of E1 (counting from zero).

+5
source

b is known as an index, which is a number. That way you can treat it as a whole. a[b] will refer to the bth element of the array a .

*(a + b) will give the value in (a + (b * sizeof(data type of array element)))

0
source

Several types may work due to implicit conversion.

A char will be incremented to int . An int or unsigned int will also work. short or unsigned short are also valid.

Even if a[b] matches *(a + b) , b cannot be a pointer, because a already a pointer. The binary + operator does not accept two pointers.

0
source

Source: https://habr.com/ru/post/1492953/


All Articles