M
Martin Dickopp
Sean Kenwrick said:Sean Kenwrick said:Martin Dickopp said:Christopher Benson-Manica wrote:
This function is intended to print a string guaranteed to be
in the form MM/DD/YYYY (assume <stdio.h> and <string.h> are
included) as YYYY-MM-DD:
void printdate( const char *date )
{
char tdate[10], *cp;
int mod=10, i;
cp=tdate;
for( i=6 ; i%mod != 5 ; ++i, ++cp ) {
if( !(i%mod) )
*(cp++)='-';
*cp=date[i%mod];
}
*cp=0;
*strchr( tdate, '/' )='-';
printf( "New date is %s\n", tdate );
}
/*
This function is intended to print a string guaranteed to be in the
form MM/DD/YYYY (assume <stdio.h> and <string.h> are included) as
YYYY-MM-DD:
*/
void printdate(const char *date)
{
printf( "New date is %s-%.2s-%.2s\n", strrchr(date, '/') + 1, date,
strchr(date, '/') + 1);
}
Jeremy.
I like this - very clever - but it relies on 'C' calling convention of
passing arguments to functions in reverse order (but so what).
There is no such convention in C, and the code doesn't make the assumption
that there is.
Doh! Of course your right, I missed the fact that the first call was to
strrchr() rather than strchr() and so I couldn;t quite figure out the logic
until my brain suggested that the calls must be going in the reverse order
(which still wouldn't work (damn this stupid brain!)).
The order in which the `strrchr' and `strchr' calls happen is unspecified,
but that doesn't matter, since neither function has any side effects.
Actually, I just thought about this again and realised I was right the first
time about the C calling convention. Check out this code:
#include <stdio.h>
void myfunc(int, int);
int main(){
int i=0;
myfunc(++i,i+=8);
}
void myfunc(int a,int b){
printf("a=%d b=%d\n",a,b);
}
Do you think it will print out a=1, b=9 or a=9, b=8 ???
I think it will print nothing, but it will make daemons fly out of my
nose.
Its the latter,
No, it's not. `++i' and `i+=8' both modify the same object `i', and since
there is no intervening sequence point, the program invokes undefined
behavior. Virtually /anything/ can happen.
(although I agree his solution didn't rely on this calling convention)
The only "calling convention" the C language has is that the arguments to
a function call are evaluated in unspecified order, and that there is
sequence point immediately before the function is called.
Martin