2

This seems to work in GCC and Visual C without comment:

static const **unsigned** char foo[] = "bar";

This is a salt being used in a unit test. There are other ways to do it, but this is simplest and involves the least casting down the line.

Will this cause trouble with other compilers?

08Dc91wk
  • 4,254
  • 8
  • 34
  • 67
  • What are you worried about, why would it cause any trouble? – Clarus Jul 27 '15 at 19:52
  • @Claris: Because a string literal represents an array of (plain) `char`. Normally you wouldn't be able to use an array of `char` to initialize an array of `unsigned char` -- but there's an explicit rule allowing it. – Keith Thompson Jul 27 '15 at 20:08

1 Answers1

4

This is safe, at least if you're using a conforming C compiler.

N1570 6.7.9 paragraph 14 says:

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

The C90 standard has essentially the same wording, so you don't need to worry about older compilers.

The character types are char, signed char, and unsigned char.

Interestingly, there's no corresponding guarantee for pointer initialization, so this:

const char *ptr = "hello";

is safe, but this:

const unsigned char *uptr = "hello";

is not -- and there doesn't seem to be a simple workaround.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • 4
    Tongue in cheek: The pointers should be `const` because the strings they point at are constants. But fixing that trivial omission doesn't fix the problem you're driving at. – Jonathan Leffler Jul 27 '15 at 20:00
  • `(const unsigned char *)"hello"` would be a simple workaround – M.M Jul 27 '15 at 21:24
  • @MattMcNabb: Probably. It does rely on some assumptions about the representations of `char` and `unsigned char`, but I think those assumptions are justified by the guarantees in the standard. (Feels a bit icky, though.) – Keith Thompson Jul 27 '15 at 22:28