Re: Is This How It's SUPPOSED to Work?
From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 01/16/04
- Next message: Thomas Matthews: "Re: Source level debugger features."
- Previous message: Arthur J. O'Dwyer: "Re: Is This How It's SUPPOSED to Work?"
- In reply to: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Next in thread: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Reply: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Thomas Matthews: "Re: Source level debugger features."
- Previous message: Arthur J. O'Dwyer: "Re: Is This How It's SUPPOSED to Work?"
- In reply to: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Next in thread: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Reply: Jerry Coffin: "Re: Is This How It's SUPPOSED to Work?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|