Reputation: 53
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
Upvotes: 4
Views: 990
Reputation: 30936
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.
Upvotes: 2
Reputation: 234875
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++?).
Upvotes: 5