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.
Martin
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!)).
Sean
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 ???
Its the latter, so I should trust my brain a little more !!! (although I
agree his solution didn't rely on this calling convention)
Sean