Macro definition to determine big endian or little endian machine?

Code supporting arbitrary byte orders, ready to be put into a file called order32.h: #ifndef ORDER32_H #define ORDER32_H #include <limits.h> #include <stdint.h> #if CHAR_BIT != 8 #error “unsupported char size” #endif enum { O32_LITTLE_ENDIAN = 0x03020100ul, O32_BIG_ENDIAN = 0x00010203ul, O32_PDP_ENDIAN = 0x01000302ul, /* DEC PDP-11 (aka ENDIAN_LITTLE_WORD) */ O32_HONEYWELL_ENDIAN = 0x02030001ul /* Honeywell 316 (aka … Read more

Macro vs Function in C

Macros are error-prone because they rely on textual substitution and do not perform type-checking. For example, this macro: #define square(a) a * a works fine when used with an integer: square(5) –> 5 * 5 –> 25 but does very strange things when used with expressions: square(1 + 2) –> 1 + 2 * 1 … Read more

C++ preprocessor __VA_ARGS__ number of arguments

I usually use this macro to find a number of params: #define NUMARGS(…) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) Full example: #include <stdio.h> #include <string.h> #include <stdarg.h> #define NUMARGS(…) (sizeof((int[]){__VA_ARGS__})/sizeof(int)) #define SUM(…) (sum(NUMARGS(__VA_ARGS__), __VA_ARGS__)) void sum(int numargs, …); int main(int argc, char *argv[]) { SUM(1); SUM(1, 2); SUM(1, 2, 3); SUM(1, 2, 3, 4); return 1; } void sum(int numargs, … Read more

Comma in C/C++ macro

If you can’t use parentheses and you don’t like Mike’s SINGLE_ARG solution, just define a COMMA: #define COMMA , FOO(std::map<int COMMA int>, map_var); This also helps if you want to stringify some of the macro arguments, as in #include <cstdio> #include <map> #include <typeinfo> #define STRV(…) #__VA_ARGS__ #define COMMA , #define FOO(type, bar) bar(STRV(type) \ … Read more

#ifdef vs #if – which is better/safer as a method for enabling/disabling compilation of particular sections of code?

My initial reaction was #ifdef, of course, but I think #if actually has some significant advantages for this – here’s why: First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example – Often, I want longer timeouts when debug is enabled, so using #if, I can write this DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000); … instead … Read more

What does ## (double hash) do in a preprocessor directive?

## is the preprocessor operator for concatenation. So if you use DEFINE_STAT(foo) anywhere in the code, it gets replaced with struct FThreadSafeStaticStat<FStat_foo> StatPtr_foo; before your code is compiled. Here is another example from a blog post of mine to explain this further. #include <stdio.h> #define decode(s,t,u,m,p,e,d) m ## s ## u ## t #define begin … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)