3 ms·
Did it say "free of side effects"? Seems trivial to me. #include <stdio.h> /* works for all signed integers, but isn't particularly useful */ int f(int
by lazyjones 13y ago
Did it say "free of side effects"? Seems trivial to me.
#include <stdio.h>
/* works for all signed integers, but isn't particularly useful */
int f(int n)
{
static int b;
return b = !b ? n : -n;
}
int main()
{
int n=-1234;
/* int n=1234; */
printf("%d\n", f(f(n)));
}
- danbruc 13y agoJust look at the answers - all tricks you can come up with are there, this one included.
- lazyjones 13y agoIndeed, I didn't look that far down, thanks. Too many FP purists on SO apparently. ;-)
- danbruc 13y agoThis wasn't intended to sound that rude - it just happens that I know this question quite well because I wrote one of the first answers. I was just a bit »WtF!?! Why is everybody posting solutions that are already there?« turning this discussion into a unreadable mess within minutes; HN isn't really made for posting code.
- lazyjones 13y agoI'm used to seeing the "correct" answers on top at SO and since the first couple with many upvotes had deficiencies, I assumed that there were no better solutions (for my personal definition of "better" apparently!). Most of the people who posted on HN probably did the same.