c - 使用 char *、unsigned char * 和 signed char * 别名

标签 c strict-aliasing

char *(和限定的变体)可以为任何东西起别名。 是 signed char *unsigned char *(及其限定变体) 免于此?

换句话说,如果我不希望它们作为其他指针参数的别名,我了解到将 restrict 应用于 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.

charsigned charunsigned char 都是字符类型 (ref: 6.2.5/15)。前面的项目符号还回答了您关于有符号和无符号类型的问题。

请记住,固定宽度类型是 typedef,它可能引用各种其他类型,所以要小心。

关于c - 使用 char *、unsigned char * 和 signed char * 别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40575116/

相关文章:

c - 使用 if 语句的循环在 C 中无法正常工作

c++ - 为什么输出是无限的?

c - 是否可以想象,严格按照C11(或以上)标准的规定,这个程序可以优化为打印hello?

c - malloc 如何使用严格的别名 - 它只能在单个编译单元内被违反吗?

c++ - 将 "this"指针转换为另一种类型不会违反严格的别名吗?

c - 相当于 Windows getch() for Mac/Linux crashes

c++ - 如何发出包含 'suspicious' 和 '-Wmain' 字样的警告?

c - 如何解析每行包含一长串数字的文件?

c++ - UNIX sockets::recv、std::byte 和严格别名

c - 通过示例了解限制限定符