PSkocik PSkocik - 23 days ago 6
C Question

Aliasing with char *, unsigned char * and signed char *

A

char *
(and qualified variants) may alias anything.
Are
signed char *
and
unsigned char *
(and their qualified variants)
exempt from this?

In other words, I've learned it's a good idea to apply
restrict
to
char*
function arguments if I don't expect them to alias pointer parameters of other types (because they could alias them):

int func(struct foo *f, char * restrict s /*different object*/);


can I drop the
restrict
keyword for signed and unsigned char variants like so?

int sfunc(struct foo *f, signed char *s /*different object*/);
int ufunc(struct foo *f, unsigned char *s /*different object*/);


Also may pointers to a signed and unsigned variant of the same type
alias each other? In other words if I expect a pointer to an int and a pointer to an unsigned and they should point to different objects, should the
int *
and
unsigned *
parameters each be
restrict
-qualified?

/* i and u should be different */
int uifunc(int * /*restrict?*/ i, unsigned * /*restrict?*/ u);

M.M M.M
Answer

The rule is (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 and unsigned char are all character types (ref: 6.2.5/15). The earlier bullets also answer your question about signed and unsigned types.

Bear in mind that the fixed width types are typedefs which may refer to various other types, so take care there.