I am a new programmer in C/C++ having programmed in Java for quite a while. I am currently understanding some C code. Here I am seeing some macro definitions like:
/* Flags for ds_flags */
#define DSF_OVER (1<<0)
#define DSF_DISPLAY (1<<1)
#define DSF_CALLFLOW (1<<2)
I am not able to understand why do we have to define these macros in such a manner. What is the advantage gained in these rather than in defining like:
#define DSF_OVER 0
#define DSF_DISPLAY 1
#define DSF_CALLFLOW 2
Some times the position of the bits represent some bit operations like in your case:
If you were to add a new item later, you will do it as
You cant have a value 5 here since it is two bits enabled (101 in binary). To avoid such potential errors it is always safe to use macros using
>>. It can’t produce a value of 5 (101) by error in when the next bit should be 1000 in binary.It is all about programming convenience to produce error free code.