Reputation: 6883
is there some trick to define a constant string literal without a trailing '\0'
character?
#define ARRAY_LEN(array) (sizeof(array)/sizeof((array)[0]))
static const char c_seqence[] = "___----__--_-_";
So that using ARRAY_LEN(c_seqence)
returns the actual sequence length without the '\0'
?
No runtime ovearhead should be generated.
Obiously the string like representation is preffered to a char array {'_','_',...}
initialization because of better readability.
C solution is preffered but may be also some c++ solution may be interesting as long they do not rely on c++11 features.
Upvotes: 3
Views: 348
Reputation: 31172
In C++11, without macros:
template <typename T, size_t n>
constexpr size_t array_length(const T (&)[n]) {
return n;
}
template <typename T, size_t n>
constexpr size_t string_length(const T (&)[n]) {
return n - 1;
}
I realize the question explicitly eliminates C++11 but that might not be true about everyone reaching this question from a search engine.
Upvotes: 0
Reputation: 21223
Is there some trick to define a constant string literal without a trailing '\0' character?
In C, if you specify the size of a character array to be one less than the size of the string literal initializer, it won't have a trailing null character. You could do it like so:
static const char c_seqence[ARRAY_LEN("___----__--_-_")-1] = "___----__--_-_";
Of course, to avoid having to indicate the string literal twice in the same line, you might want to define a macro to do it:
#define MAKE_STR_LITERAL(n, l) static const char n[ARRAY_LEN(l)-1] = l
You can use it like this:
MAKE_STR_LITERAL(c_seqence, "___----__--_-_");
Note:
As stated in https://stackoverflow.com/a/4348188/2793118, this behavior is in section 6.7.8 of the standard (quoting from that answer):
§ 6.7.8p14
An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character 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.
Note2: Turns out this is a C-only thing. In C++ it will not compile. Yet another great example of why people shouldn't tag questions with both C and C++.
Upvotes: 5
Reputation: 37192
The simplest solution is to change your array length macro to ignore the trailing null:
#define ARRAY_LEN(array) (sizeof(array)/sizeof((array)[0]) - 1)
(posted under duress :)
Upvotes: 2