Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array indexing and usual arithmetic conversion

In C, when I use an integer as an array index, does this trigger usual arithmetic conversion rules to convert the array index to some integer type? If so, which integer type does it get converted to?

Example 1:

int i = ...;
... a[i] ...

Does this trigger an integer conversion or promotion? If so, what type is i converted to? (unsigned int? size_t? something else?)

Example 2:

unsigned int j = ...;
... b[j] ...

Does this trigger an integer conversion or promotion? If so, what type is i converted to?

What if the type of the index is something other than int? What are the rules for when it undergoes integer conversion? Are the usual arithmetic conversion rules applied, or something?

I am also interested in the same question about pointer arithmetic, e.g., the expression p+i where p is a pointer and i is some integral type.

I've looked at the CERT Secure Coding guidelines on understanding integer conversions and the OWASP overview of integer overflow, but neither resource describes this case. Neither does the following StackOverflow question: Integer conversions(narrowing, widening), undefined behaviour.

like image 717
D.W. Avatar asked Jan 22 '26 14:01

D.W.


1 Answers

Section 6.5.2.1, paragraph 2 of C99 says:

... The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2)))...

Which implies rules for the + apply:

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

So, when first argument for + is a pointer the second must have an integer type and no conversion is being made.

Note:

E2 in the frist quote is expression, and as such can contain many type conversion as it's computed. The important thing is that the resulting type is an integer type.

like image 107
virtus Avatar answered Jan 25 '26 08:01

virtus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!