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?

2
  • What are you worried about, why would it cause any trouble? Commented Jul 27, 2015 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. Commented Jul 27, 2015 at 20:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
(const unsigned char *)"hello" would be a simple workaround
@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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.