I am rather new to using some advanced concepts in C. I am trying to understand the code from an API that uses _
, >>
and <<
. I understand _
is used as a reserved identifier, >>
is used for a bitwise right, and <<
is used for a bitwise left shift.
But what I am wondering is how do we know what data type argument does OFFSET_AND_ROUND2
accepts? and how and why the function does the bitwise operation for offset and rounding?. Lastly, why I am getting the error invalid operands?
Please find the code below:
#include <stdio.h>
#define OFFSET_AND_ROUND2(_a, _b) (((_a)+(1<<((_b)-1))-((_a)<0?1:0))>>(_b))
int main()
{
printf("Hello World\n\n");
printf("%d", OFFSET_AND_ROUND2(3.87,2));
return 0;
}
Please find the error message below:
main.c:10:69: error: invalid operands to binary >> (have 'double' and 'int')
#define OFFSET_AND_ROUND2(_a, _b) (((_a)+(1<<((_b)-1))-((_a)<0?1:0))>>(_b))
^
main.c:15:18: note: in expansion of macro 'OFFSET_AND_ROUND2'
printf("%d", OFFSET_AND_ROUND2(3.87,2));
^
I look forward to learning a little more about C, thanks!
When using macros the preprocesser takes the content of the macro and replaces each occurence. As an example:
#define A 5
...
int a = A;
gets translated to
int a = 5;
The same is for parameters:
#define A(_a) (_a+1)
...
int a = A(2);
gets translated to
int a = (2+1);
In the end it doesn't matter which data types are used as long they support all needed operations. The error is because you can't shift floats/doubles in c++
Because it works like search & replace it is pretty important to use brackets if necessary:
#define ADD(_a,_b) _a+_b
...
int a = ADD(5,4) * 3;
gets translated to
int a = 5+4 * 3 // = 5 + (4 * 3) = 17
while (5+4)*3 = 27