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

Viewed 71

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?

3 Answers

In this context "an expression that has integer type" refers to any integer type, e.g. signed or unsigned char, short, int, long, or long long, as well as any other integer types defined by the implementation.

So you can safely use arguments of type int or unsigned int with a pointer, provided the resulting pointer still points to the same object or array.

int = 1 and unsigned int = 1 are same thing, int = -1 and ungisned int = -1 and not the same thing.. If you use 1, 2 and 3, the answer is yes you can "call" it int, unsigned int or whatever you want. If you want the offset to be negative for example you can't use unsigned int, or if you want the offset to be larger then 2^31, then you can't use unsigned int.

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.

Related