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

From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 01/16/04


Date: Fri, 16 Jan 2004 17:37:56 +0100

Jerry Coffin wrote:
>
> 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"));

I haven't tried it, but I don't think that the compiler
will accept it. Even if it knows not much about the argument
list, it still knows that the first argument must be a const char*.
The return value of Proper, which is a cstring, doesn't qualify for
that.

>
> (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)?

Unless I am missing something, it works because the address returned
from Proper, which is the address of a cstring object, is the same
as the address of its first member. Don't know if this is guaranteed
in C. In C++ it is not. (BTW: MS uses this technique in their CString
class).

-- 
Karl Heinz Buchegger
kbuchegg@gascad.at


Relevant Pages

  • Re: Is This How Its SUPPOSED to Work?
    ... > cstring Proper(char *szIn) ... Yes, it's guaranteed work, for a sufficiently limited definition of work ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Use std::string with printf/sprintf etc.
    ... Just make the data member which holds the char* or ... TCHAR* the first member ... the pointer, or va_arg won't correctly find the following argument. ... I belive CString achieves this by storing additional housekeeping ...
    (microsoft.public.vc.stl)