使用 char *、unsigned char * 和 signed char * 别名
Aliasing with char *, unsigned char * and signed char *
A char *
(和限定的变体)可以为任何东西起别名。
是 signed char *
和 unsigned char *
(及其限定的变体)
免于此?
换句话说,如果我不希望它们为其他类型的指针参数设置别名(因为它们可以别名他们):
int func(struct foo *f, char * restrict s /*different object*/);
我可以像这样删除有符号和无符号字符变体的 restrict
关键字吗?
int sfunc(struct foo *f, signed char *s /*different object*/);
int ufunc(struct foo *f, unsigned char *s /*different object*/);
也可以指向相同类型的有符号和无符号变体
互为别名?换句话说,如果我期望一个指向 int 的指针和一个指向 unsigned 的指针,并且它们应该指向不同的对象,那么 int *
和 unsigned *
参数都应该是 restrict
限定的吗?
/* i and u should be different */
int uifunc(int * /*restrict?*/ i, unsigned * /*restrict?*/ u);
规则是 (C11 6.5/7):
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the object,
- a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
- a character type.
char
、signed char
和 unsigned char
都是字符类型 (ref: 6.2.5/15)。前面的项目符号还回答了有关有符号和无符号类型的问题。
请记住,固定宽度类型是 typedef,它可能引用其他各种类型,所以要小心。
A char *
(和限定的变体)可以为任何东西起别名。
是 signed char *
和 unsigned char *
(及其限定的变体)
免于此?
换句话说,如果我不希望它们为其他类型的指针参数设置别名(因为它们可以别名他们):
int func(struct foo *f, char * restrict s /*different object*/);
我可以像这样删除有符号和无符号字符变体的 restrict
关键字吗?
int sfunc(struct foo *f, signed char *s /*different object*/);
int ufunc(struct foo *f, unsigned char *s /*different object*/);
也可以指向相同类型的有符号和无符号变体
互为别名?换句话说,如果我期望一个指向 int 的指针和一个指向 unsigned 的指针,并且它们应该指向不同的对象,那么 int *
和 unsigned *
参数都应该是 restrict
限定的吗?
/* i and u should be different */
int uifunc(int * /*restrict?*/ i, unsigned * /*restrict?*/ u);
规则是 (C11 6.5/7):
An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of the object,
- a type that is the signed or unsigned type corresponding to the effective type of the object,
- a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
- an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
- a character type.
char
、signed char
和 unsigned char
都是字符类型 (ref: 6.2.5/15)。前面的项目符号还回答了有关有符号和无符号类型的问题。
请记住,固定宽度类型是 typedef,它可能引用其他各种类型,所以要小心。