3

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

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
Bobby
  • 43
  • 2

2 Answers2

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++?).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    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. – ad absurdum Feb 01 '18 at 16:09
  • @DavidBowling: Oops. Yet another difference between C and C++. – Bathsheba Feb 01 '18 at 16:12
  • Oh yeah, I forgot that this is one of the things that C++ got right ;) – ad absurdum Feb 01 '18 at 16:13
  • 1
    @DavidBowling: But they ruined the language with a `bool` type! – Bathsheba Feb 01 '18 at 16:13
  • @EugeneSh.: I think its introduction was an act of pure devilry, and has led to things like `std::vector`. Especially since sizeof(bool) could be larger than sizeof(char). – Bathsheba Feb 01 '18 at 16:15
  • Well, I am not interacting with C++ too much so I might not be exposed to the nuances. Will take your word on it :) – Eugene Sh. Feb 01 '18 at 16:16
  • 1
    @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. – Bathsheba Feb 01 '18 at 16:18
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.

user2736738
  • 30,591
  • 5
  • 42
  • 56