4

Just a quick question for which I fail in finding proper answer.

If I want to declare a const text variable, is it absolutely equal to do:

const char my_variable [] = {'t', 'e', 's', 't', 0};

or

const char my_variable [] = "test";

Many thanks in advance

5
  • Yes, these are equivalent. Just make sure to make the distinctions as in my older question Commented Feb 1, 2018 at 16:01
  • @EugeneSh. Nice plug. Have an upvote. Commented Feb 1, 2018 at 16:06
  • Since the character array is constant I would instead define const char *my_variable = "test"; Commented Feb 1, 2018 at 16:27
  • 1
    @AugustKarlstrom There are different usecases. Note the difference in behavior when using sizeof, for example. Commented Feb 1, 2018 at 16:31
  • @EugeneSh. That's true, sizeof is more efficient than strlen. Commented Feb 1, 2018 at 16:52

2 Answers 2

5

Yes, the two declarations are identical.

"test" is a char[5] type in C, with elements 't', 'e', 's', 't', and 0.

(Note that in C++, the type is a const char[5]: yet another difference between the two languages. See What is the type of string literals in C and C++?).

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

7 Comments

The characters of a string literal are stored (in static storage) in arrays of type char, not const char, so "test" is a char[5] type, but it is UB to attempt to modify it.
@DavidBowling: Oops. Yet another difference between C and C++.
Oh yeah, I forgot that this is one of the things that C++ got right ;)
@DavidBowling: But they ruined the language with a bool type!
@EugeneSh. One issue is that things like (a == b) + (b == c) is an int in C and C++, but a == b is a bool in C++. C is a model of consistency in this respect.
|
2

From standard 6.7.9p14: (Supporting the other answer)

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.

So yes both of them are achieving the same thing.

Comments

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.