Search code examples
cpointersintegerpointer-arithmetic

C: int or unsigned int which type I used for pointer increasement


For this situation:

int arr[] = {0, 1, 2};
void func (int* arr_in){
  int offset_0 = 0;
  int offset_1 = 1;
  int offset_2 = 2;
  printf("%d\n", *(arr_in + offset_0) );
  printf("%d\n", *(arr_in + offset_1) );
  printf("%d\n", *(arr_in + offset_2) );
}

The compiler will not complain whether the I use is int or unsigned.

Two of results also seems correctly.

$ clang test.c -Wall -o test

I refer to the chapter §6.5.6/8 in the draft C11:

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.

In the draft, there is no mention of "integer" which is (signed)int or unsigned.

So both there can be used for pointer operand on all platform?


Solution

  • Just read the C Standard carefully.

    From the C Standard (6.2.5 Types)

    17 The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types. The integer and real floating types are collectively called real types.

    and now you can reread your quote from the C Standard

    When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.

    So you may use even the type char that is neither signed or unsigned integer type.