C: int 或 unsigned int 我使用哪种类型来增加指针
C: int or unsigned int which type I used for pointer increasement
对于这种情况:
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) );
}
无论我用的是int
还是unsigned
,编译器都不会报错。
两个结果似乎也是正确的。
$ clang test.c -Wall -o test
我参考C11草案中的§6.5.6/8章节:
When an expression that has integer type is added to or subtracted from a pointer, the
result has the type of the pointer operand.
在草案中,没有提到“整数”,即(已签名)int
或unsigned
。
所以两者都可以用于所有平台上的指针操作数?
在此上下文中,“具有整数类型的表达式”指的是 any 整数类型,例如signed
或 unsigned
char
、short
、int
、long
或 long long
,以及定义的任何其他整数类型通过实施。
因此您可以安全地将 int
或 unsigned int
类型的参数与指针一起使用,前提是生成的指针仍指向同一对象或数组。
int = 1
和 unsigned int = 1
是一回事,int = -1
和 ungisned int = -1
不是一回事。如果你使用 1、2 和 3,答案是是的,您可以“调用”它 int
、unsigned int
或任何您想要的名称。如果您希望偏移量为负,例如您不能使用 unsigned int
,或者如果您希望偏移量大于 2^31
,则您不能使用 unsigned int
。
请仔细阅读 C 标准。
来自 C 标准(6.2.5 类型)
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.
现在您可以重新阅读 C 标准中的引用
When an expression that has integer type is added to or subtracted
from a pointer, the result has the type of the pointer operand.
所以你甚至可以使用既不是有符号整数也不是无符号整数类型的char
类型。
对于这种情况:
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) );
}
无论我用的是int
还是unsigned
,编译器都不会报错。
两个结果似乎也是正确的。
$ clang test.c -Wall -o test
我参考C11草案中的§6.5.6/8章节:
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.
在草案中,没有提到“整数”,即(已签名)int
或unsigned
。
所以两者都可以用于所有平台上的指针操作数?
在此上下文中,“具有整数类型的表达式”指的是 any 整数类型,例如signed
或 unsigned
char
、short
、int
、long
或 long long
,以及定义的任何其他整数类型通过实施。
因此您可以安全地将 int
或 unsigned int
类型的参数与指针一起使用,前提是生成的指针仍指向同一对象或数组。
int = 1
和 unsigned int = 1
是一回事,int = -1
和 ungisned int = -1
不是一回事。如果你使用 1、2 和 3,答案是是的,您可以“调用”它 int
、unsigned int
或任何您想要的名称。如果您希望偏移量为负,例如您不能使用 unsigned int
,或者如果您希望偏移量大于 2^31
,则您不能使用 unsigned int
。
请仔细阅读 C 标准。
来自 C 标准(6.2.5 类型)
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.
现在您可以重新阅读 C 标准中的引用
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand.
所以你甚至可以使用既不是有符号整数也不是无符号整数类型的char
类型。