Morris Keesan
4/19/2011 9:08:00 PM
On Tue, 19 Apr 2011 16:54:09 -0400, dr.oktopus
<blindwilly@freeonline.zzn.com> 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" };
>
> and
>
> #define MESSAGE_LEN (strlen(messages[0])
Besides the missing close parenthesis: defining MESSAGE_LEN this way,
you're not precomputing the length of the strings. Every time you write
MESSAGE_LEN in your code, this will result in a call to strlen().
> 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")
I prefer the second approach, because then MESSAGE_LEN really is a
constant, and you compute it at compile time rather than while the
program is running. If it were me, I would also put in somewhere
a line that says
assert(sizeof message_lo == sizeof message_up);
[Note how, in answering your message, I've included all of the context
that a reader of my message needs in order to understand what I'm saying,
rather than assuming that said reader is using Google groups and has easy
access to your message.]
--
Morris Keesan -- mkeesan@post.harvard.edu