On 4/19/2011 4:54 PM, dr.oktopus wrote:
> Hello,
> here I am talking about having good habits in code writing.
> I have a simple problem: have two messages that represent
> the same string, one in lowercase and the other in uppercase
> letter. Under some circustamces, I want to print the first or
> the second, so I couple them inside an array and use a
> variable "allcaps" as index.
> And I have to precompute the length of the strings, that are CONSTANT
> strings.
>
> A solution is:
>
> const char *messages[2] = { "this is lowercase string", "this is
> uppercase string" };
Ah. This is obviously some strange usage of the word "uppercase"
that I hadn't previously been aware of.
> and
>
> #define MESSAGE_LEN (strlen(messages[0])
Missing a parenthesis, and not a "CONSTANT" in any event.
> But what if you prefer, as good habits could suggest, to rewrite
> all using only arrays and the sizeof operator?
>
> const char message_lo[] = "this is lowercase";
> const char message_up[] = "this is uppercase";
>
> #define MESSAGE_LEN (sizeof(message_lo) - 1)
>
> const char messages[2][MESSAGE_LEN] = {&message_lo,&message_hi };
>
> What is better? (I think the answer is: "none")
Neither is much good, and the second won't even compile.
It's not clear why you're so worried about CONSTANTs or about
having the strings in an array, but one possibility is
#define LOWER "this is lowercase string"
#define UPPER "THIS IS CAPITALIZED STRING"
#define MESSAGE_LEN (sizeof LOWER > sizeof UPPER \
? sizeof LOWER : sizeof UPPER)
const char messages[][MESSAGE_LEN] = { LOWER, UPPER };
I don't know whether you'll find this useful, because I don't
really understand why you've adopted all these strictures, nor
what others may lurk unposted.
--
Eric Sosman
d