I am working on converting the shift functionality implemented below into a macro
Code:
#include <stdio.h>
unsigned int shift (unsigned int value, int n)
{
if ( n > 0 )
value <<= n;
else
value >>= -n;
return value;
}
int main (void)
{
unsigned int w1 = 01777777u, w2 = 0444u;
unsigned int shift (unsigned int value, int n);
printf ("%o\t%o\n", shift (w1, 5), w1 << 5);
printf("Here is w1 %o\tHere is w1 left shifted by 1 %o\n", w1, w1 << 1);
printf ("Right Shift %o\t%o\n", shift (w1, -6), w1 >> 6);
printf ("\n above line was a right shift of w1:%o by 6", w1);
printf ("\n%o\t%o\n", shift (w2, 0), w2 >> 0);
printf ("%o\n", shift (shift (w1, -3), 3));
return 0;
}
I came up with this....
Code:
#include <stdio.h>
#define nsign(v,n) ((n) > (0) ? (v << n) : (v >> n))
int main (int argc, char **argv)
{
int w1 = 01777777u;
nsign(w1,-5);
printf("%o\n", w1);
}
Which seems to work for positive values of n, but does not seem to work for negative values of n.
How can I improve this? I have looked quite a bit. I read the preprocessor chapter of the book I follow, and a document on C preprocessor for GCC version 2 ( I know it is old, it was the only pdf on the subject I could find ) I also read parts of the GCC documentation. The examples all seem to be similar. I was looking for an example, which had a simple function and its equivalent macro. I also looked into the c library; went through a number of , perhaps half of the .c source files in hope of one macro implementation with if statements and etc. Stackoverflow has a number of very elaborate macros. But they seem to be snippets with the expectation that reader would add the rest I guess. Perhaps after reading all the content, I can understand and implement one them now but they are not exactly what I need. I did try to use what I can from them, but I run into error messages. I wanted to make sure I am not making this overly complex, and ask you for the ideal preprocessor documentation.
So 1- Could you tell me what is the appropriate term I need to search under to find the best documentation on the C preprocess 2- Is what I am doing, the ideal way to go about implementing the shift function, and if not, how can I improve it please? Do I need to implement a compound statement?
Thanks