简体   繁体   English

C: int 或 unsigned int 哪种类型我用于指针增加

[英]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 .无论我使用的是int还是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:我参考了 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.将具有 integer 类型的表达式添加到指针或从指针中减去时,结果具有指针操作数的类型。

In the draft, there is no mention of "integer" which is (signed) int or unsigned .在草案中,没有提到(有符号的) intunsigned“整数”

So both there can be used for pointer operand on all platform?那么两者都可以用于所有平台上的指针操作数吗?

In this context "an expression that has integer type" refers to any integer type, eg signed or unsigned char , short , int , long , or long long , as well as any other integer types defined by the implementation.在此上下文中,“具有 integer 类型的表达式”是指任何integer 类型,例如signedunsigned charshortintlonglong long ,以及任何其他 Z157DB7DF5660235672E85 实现定义的类型。

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.因此,您可以安全地将intunsigned int类型的 arguments 与指针一起使用,前提是生成的指针仍指向相同的 object 或数组。

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. int = 1unsigned int = 1是同一个东西, int = -1ungisned int = -1而不是同一个东西。如果你使用 1、2 和 3,答案是肯定的,你可以“调用”它intunsigned int或任何你想要的。 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 .例如,如果您希望偏移量为负数,则不能使用unsigned int ,或者如果您希望偏移量大于2^31 ,则不能使用unsigned int

Just read the C Standard carefully.请仔细阅读 C 标准。

From the C Standard (6.2.5 Types)从 C 标准(6.2.5 类型)

17 The type char, the signed and unsigned integer types, and the enumerated types are collectively called integer types. 17 char类型、有符号和无符号integer类型、枚举类型统称为integer类型。 The integer and real floating types are collectively called real types. integer 和实浮点类型统称为实类型。

and now you can reread your quote from the C Standard现在您可以从 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.将具有integer 类型的表达式添加到指针或从指针中减去时,结果具有指针操作数的类型。

So you may use even the type char that is neither signed or unsigned integer type.因此,您甚至可以使用既不是签名也不是无符号 integer 类型的char类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM