Re: Is This How It's SUPPOSED to Work?

From: Jerry Coffin (jcoffin_at_taeus.com)
Date: 01/16/04


Date: Fri, 16 Jan 2004 15:50:33 GMT

In article <Pine.GSO.4.58-035.0401152239460.621
@chloroprene.ww.andrew.cmu.edu>, ajo@nospam.andrew.cmu.edu says...

[ ... ]

> Hey, C can almost do this too; it's just not idiomatic (probably
> because of that "almost"). ;-)
>
> typedef struct {
> char c_str[1000];
> } cstring;
>
> cstring Proper(char *szIn)
> {
> cstring s = {0};
> strncat(s.c_str, szIn, sizeof s.c_str);
> return s;
> }
>
> printf("%25s %25\n", Proper("FRED JONES").c_str,
> Proper("ALICE SMITH").c_str);
>
> I *think* this is guaranteed to work. But I've never tried
> it, and it's not as easily understood as the other ways.
> Expert commentary welcomed.

Yes, it's guaranteed work, for a sufficiently limited definition of work
-- specifically, you've placed an arbitrary limit on the maximum length
of string with which it'll work.

Silly pop quiz of the day: given your definition of Proper, why is this
guaranteed to work:

printf(Proper("FRED JONES"));

(even though the '.cstr' has been omitted), but this:

printf("%s\n", Proper("FRED JONES"));

gives undefined behavior (though it will probably still work as expected
on nearly all implementations)?

-- 
    Later,
    Jerry.
The universe is a figment of its own imagination.


Relevant Pages

  • Re: Is This How Its SUPPOSED to Work?
    ... > Yes, it's guaranteed work, for a sufficiently limited definition of work ... > Silly pop quiz of the day: given your definition of Proper, ... from Proper, which is the address of a cstring object, is the same ... as the address of its first member. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Is This How Its SUPPOSED to Work?
    ... >Hey, C can almost do this too; ... >cstring Proper(char *szIn) ...
    (alt.comp.lang.learn.c-cpp)