Date: Mon, 29 Jan 2001 01:31:45 +0100 From: Thomas Moestl <tmoestl@gmx.net> To: freebsd-chat@freebsd.org Subject: Re: C Puzzle Message-ID: <20010129013145.A4834@crow.dom2ip.de> In-Reply-To: <20010128161353.C98223@trollkarl.skafte.org>; from skafte%2Bfreebsd-chat@trollkarl.net on Sun, Jan 28, 2001 at 04:13:53PM -0700 References: <20010128161353.C98223@trollkarl.skafte.org>
next in thread | previous in thread | raw e-mail | index | archive | help
On Sun, Jan 28, 2001 at 04:13:53PM -0700, Greg Skafte wrote:
> doesn't work :
>
> char* fn_mtrim __P((char*));
> char* fn_mtrim (s)
> char* s ;{
> short i=0;
> char *buffer= (char *) calloc (256,sizeof(char));
> while (*s){
> ( *s == ' ') ? s*++ : buffer[i++] = *s++ ;
> };
> return buffer;
> }
>
> works :
>
> char* fn_mtrim __P((char*));
> char* fn_mtrim (s)
> char* s ;{
> short i=0;
> char *buffer= (char *) calloc (256,sizeof(char));
> while (*s){
> ( *s != ' ') ? buffer[i++] = s*++ : *s++ ;
> };
> return buffer;
> }
>
> Why does the first one not work and the second one work ....
Precedence tells us:
( *s == ' ') ? *s++ : buffer[i++] = *s++ ;
is equivalent to
(( *s == ' ') ? *s++ : buffer[i++]) = *s++ ;
(notice the outer brackets). I guess you mean *s++ when you write s*++.
If you try this with string literal as argument (fn_mtrim("foo bar")),
the string will get written into, and this may even segfault using gcc.
Otherwise, the result will be wrong anyway, because s gets incremented
before it is tested against ' ' (this is not really well-defined), and
then incremented again when *s == ' ' and the value is assigned to *s++.
- thomas
P.S.: this is really ugly ;-)
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-chat" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20010129013145.A4834>
