Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper input datatype for the operator []?

Tags:

arrays

c

memory

When accessing an array we use the operator [] like so:

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

What is the proper data type for the variable b above?

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

like image 319
zztops Avatar asked Jan 13 '23 20:01

zztops


1 Answers

From the C standard(ISO/IEC 9899:TC2) Sec 6.5.2.1 Array subscripting

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

like image 193
Jeyaram Avatar answered Jan 17 '23 07:01

Jeyaram