by voidlogic · 13y ago · 0 comments
So much of this stuff is the kind of thing people new to C should not be doing. Minimizing use of preprocessor directives leads to more maintainable C. Use them where they are needed and not anywhere else.
Also, for the swapping they show:
a = a ^ b;
b = a ^ b;
a = a ^ b;
They fail to point out it's (platform dependent) performance implications. The above code is faster then the below code on PowerPC/POWER for example, but slower on x86/amd64. int tmp = a; //or: register int tmp = a;
a = b;
b = tmp;In other languages I use, I can get better by studying the source of programmers better than me. With C this is risky, as many large projects have messy code bases, and through their complexity hide the fact that one of C's great features is that it can be extremely lightweight in some projects. The tricks skilled C programmers use are a mix on unadvised hacks (like xor swap) and truly clever, portable, advised concepts.
There's also no great C book on higher-level C. Deep C Secrets is good, but perhaps a bit old. If you're using C for data work, you're out of luck (with maybe the exception of Ben Klemen's book, Modelling with Data, which is good but almost uses C too much when a bit of R and python would help). I'd love a book of machine learning and/or computational algorithms in C — with direct data examples.
Read a into register1
Read b into register2
Write register1 to a
Write register2 to b
Whereas with the xor, you read the values, then do some pointless xoring, then write them back out. Further, if you are using a and b for anything else, the 'tmp' turns into a simple register renaming, for 0 cost!While ^ swapping makes sense in assembler, it never makes sense in C.