Macro inside Macro - c

Consider the following code:
#define P1(x) x+x
#define P2(x) 2*P1(x)
int main()
{
int a = P1(1) ? 1 : 0;
int b = P2(a)&a;
return 0;
}
Now, I thought that the compiler first replacing the macros with their values and so int b = 2*a+a&a; (and since a=1 then b=3). Why isn't it so?

This is because & has lower precedence than that of addition + operator. The grouping of operands will take place as
int b = ( (2*a + a) & a );
Therefore, (2*a + a) = 3 and 3 & 1 = 1 (011 & 001 = 001).

There's no precedence in your operation (it is just a textual substitution) thus, as you've noted,
#define P1(x) x+x
#define P2(x) 2*P1(x)
int a = P1(1) ? 1 : 0; // 1
and since & has lower precedence than +, it is equivalent to
int b = ((2 * a) + a) & a;
i.e. only the rightmost bit is set on b.
((2 * a) + a) 011 &
a 001 =
--------------------
b 001

Related

C symbolic constant wrong value [duplicate]

Example
#define Echo(a) a
#define Echo(a) (a)
I realize there probably isn’t a significant difference here, but why would you ever want to include the a within parenthesis inside the macro body? How does it alter it?
Suppose you have
#define mul(x, y) x * y
What happens if I say:
mul(a + 5, 6); /* a + 5 * 6 */
Now if I slighlty change the macro:
#define mul(x, y) ((x) * (y))
mul(a + 5, 6); /* ((a + 5) * (6)) */
Remember, the arguments aren't evaluated or anything, only textual substitution is performed.
EDIT
For an explanation about having the entire macro in parentheses, see the link posted by Nate C-K.
Just for the record, I landed from Here How to fix mathematical errors while using macros and I will try to expand this Answer here to fit the Other one.
You are asking about the difference about:
#define Echo( a ) a
#define Echo( a ) ( a )
which is fine as long as you do not understand the macro it self (I am not an expert too :) ).
First of all you already (probably) know that there is Operator Precedence, so there is a huge difference of this two programs:
1):
#include <stdio.h>
#define ADD( a , b ) a + b
int main( void )
{
auto const int a = 5;
auto const int b = 10;
auto const int c = ADD ( 2 + a , 2 + b );
printf( "%d", c );
return 0;
}
Output:
19
and:
#include <stdio.h>
#define ADD( a , b ) ( a ) + ( b )
int main( void )
{
auto const int a = 5;
auto const int b = 10;
auto const int c = ADD ( a , b );
printf( "%d", c );
return 0;
}
Output:
15
Now lets preplace + with *:
#define ADD( a, b ) a * b
The compiler treats a * b like for example a == 5 and b == 10 which does 5 * 10.
But, when you say:
ADD ( 2 + a * 5 + b )
Like here:
#include <stdio.h>
#define ADD( a , b ) ( a ) * ( b )
int main( void )
{
auto const int a = 5;
auto const int b = 10;
auto const int c = ADD ( 2 + a , 5 + b );
printf( "%d", c );
return 0;
}
You get 105, because the operator precedence is involved and treats
2 + b * 5 + a
as
( 2 + 5 ) * ( 5 + 10 )
which is
( 7 ) * ( 15 ) == 105
But when you do:
#include <stdio.h>
#define ADD( a, b ) a * b
int main( void )
{
auto const int a = 5;
auto const int b = 10;
auto const int c = ADD ( 2 + a , 5 + b );
printf( "%d", c );
return 0;
}
you get 37 because of
2 + 5 * 5 + 10
which means:
2 + ( 5 * 5 ) + 10
which means:
2 + 25 + 10
Short answer, there is a big difference between:
#define ADD( a , b ) a * b
and
#define ADD( a , b ) ( a ) * ( a )

Explanation for output of given code

#include <stdio.h>
int sum(int a, int b, int c) {
return a + b + c / 2;
}
void main() {
int (*function_pointer)(int, int, int); // how this will be interpreted
function_pointer = sum;
printf("%d", function_pointer(2, 3, 4));
return ;
}
When i ran on ide it gave output 7, i dont understand how?
The statement
int (*function_pointer)(int, int, int);
declares a pointer to a function that accepts three int arguments and return an int. Latter this is pointed to function sum and used to call the function.
Inside the sum function the statement
return a + b + c / 2;
is parsed as
return a + b + (c / 2); // division operator has higher precedence than + operator
// and therefore the operands `c` and `2` will be bind to `/` operator
this:
int (*function_pointer)(int, int, int);
means you are defining a function pointer with the name function_pointer that can be used as alias for ANY other function that takes 3 integers as parameter an returns an integer
then when you do this:
function_pointer = sum;
you are assigning the address of the function sum to the function_pointer, that means later, you can do both:
function_pointer(2, 3, 4)
or
sum(2, 3, 4)
now to the result, and why is printing out 7
a + b + c / 2
with 2,3,4 is the same as 2 + 3 + 4 / 2 or 2 + 3 + 2 = 7

Comparing two integers and insert a comparison sign <,>= between the two numbers

I would like to compare two positive integers and add a comparison sign between them. I may not use any logical, relational or bitwise operators and no if then else or while loop or ternary operator.
I found the max and min of these two numbers.
How can I preserve the order and still insert the comparison sign? Any ideas?
E.g.:
4 6 was entered by user output must be 4 < 6
10 2 was entered by user output must be 10 > 2
2 2 was entered by user output must be 2 = 2
f1 = x / y;
f2 = y / x;
f1 = (f1 + 2) % (f1 + 1);
f2 = (f2 + 2) % (f2 + 1);
max = f1 * x + f2 * y ;
max = max / (f1 + f2);
You can use an array of char:
#include <stdio.h>
int main(void)
{
unsigned a, b;
scanf("%u %u", &a, &b);
size_t cmp = (_Bool)(a / b) - (_Bool)(b / a);
char relation = "<=>"[cmp + 1];
printf("%u %c %u\n", a, relation, b);
return 0;
}
This approach don't require min and max found out.
Explanation:
(_Bool)exp will be 1 if exp is non-zero, and 0 if exp equals to 0.
Since a and b are positive integers, a / b will be 0 when a < b, and 1 when a >= b. See the truth table below for details.
(_Bool)(a / b) (_Bool)(b / a) (_Bool)(a / b) - (_Bool)(b / a)
a > b 1 0 1
a = b 1 1 0
a < b 0 1 -1
As a result, cmp evaluates to -1, 0, 1, like a typical comparison function. And thus, cmp + 1 will conveniently lead to 0, 1, 2 valid array indexes.
Thanks #janos for his help.
Edit:
As #chux carefully points out,
OP stated "I may not use any logical, ... operators". The C spec has
"... the logical negation operator !...". §6.5.3.3 5. Using ! may not
meet OP's goals.
So I changed !!exp to (_Bool)exp to meet OP's demand.
Edit II:
OP commented:
Thanks. This does not work when one of the inputs is 0.
But isn't the input numbers granted to be positive? Well, to handle zeros you can use size_t cmp = (_Bool)((a + (_Bool)(a - UINT_MAX)) / (b + (_Bool)(b - UINT_MAX))) - (_Bool)((b + (_Bool)(b - UINT_MAX)) / (a + (_Bool)(a - UINT_MAX)));. Don't forget to #include <limits.h>.
EDIT III (The last edit, I hope):
#include <stdio.h>
#include <limits.h>
#define ISEQUAL(x, y) (_Bool)((_Bool)((x) - (y)) - 1) // 1 if x == y, 0 if x != y
#define NOTEQUAL(x, y) (_Bool)((x) - (y)) // 0 if x == y, 1 if x != y
int main(void)
{
unsigned a, b;
printf("%u\n", UINT_MAX);
scanf("%u %u", &a, &b);
_Bool hasZero = NOTEQUAL(ISEQUAL(a, 0) + ISEQUAL(b, 0), 0);
_Bool hasMax = NOTEQUAL(ISEQUAL(a, UINT_MAX) + ISEQUAL(b, UINT_MAX), 0);
int hasBoth = ISEQUAL(hasZero + hasMax, 2);
int cmp = (_Bool)((a + hasZero + hasBoth) / (b + hasZero + hasBoth))\
- (_Bool)((b + hasZero + hasBoth) / (a + hasZero + hasBoth));
// "+ hasZero + hasBoth" to avoid div 0: UINT_MAX -> 1, while 0 -> 2.
hasBoth = 1 - hasBoth * 2; // 1 if hasBoth == 0, or -1 if hasBoth == 1
char relation = "<=>"[hasBoth * cmp + 1]; // reverse if has both 0 and UINT_MAX
printf("%u %c %u\n", a, relation, b);
return 0;
}
Fixed a bug when a == UINT_MAX - 1 and b == UINT_MAX at #chux points out.
Used macro to improve readability.
Added some comments.
As OP has x, y and has computed their minimum min and maximum max
void prt(unsigned x, unsigned y, unsigned min, unsigned max) {
// min not used
unsigned cmp = 1 + x/max - y/max;
printf("%u %c %u\n", x, "<=>"[cmp], y);
}
#include <stdio.h>
static unsigned int cmpgt(const unsigned int a, const unsigned int b)
{
return b?(a/b ? (a-b):0):a;
// if B is 0, then return A. non zero A will be treated as true
// if a is zero then is false
// if b is not zero then do a/b, if non zero then return (a-b)
// non zero (a-b) will be treated as true
// if (a-b) is zero then will be treated as false
//
// This is a very ugly way of implementing operator >
// There are other ways to do it
// But the point is, you need operator >, but you can not use it
// ( for whatever reason), then you just make it, which is doable
}
static const char *mark(const unsigned int a, const unsigned int b)
{
return cmpgt(a, b)?">":(cmpgt(b,a)?"<":"=");
// no if-else, but ternary operator is a good alternative
// so those are two nested operator ?:
// basically :
// if a>b then return ">"
// else if a<b return "<"
// else return "="
// with cmpgt/operator > implemented, this is a lot easier
}
int main(void) {
const int input[] = {1,3,4,5,5,2,3,4}; //test input
size_t input_size = sizeof(input)/sizeof(int);
for (size_t i=0;cmpgt(input_size-1, i);i++){
// while loop is banned, but for loop is still usable
// the loop condition is handled by cmpgt
printf("%d %s ",input[i],mark(input[i], input[i+1]));
}
printf("%d\n", input[input_size-1]);
return 0;
}
sample output:
1 < 3 < 4 < 5 = 5 > 2 < 3 < 4
https://ideone.com/dFHWnn
A simple compare is to use <=, >= and then lookup the compare character from a string.
void cmp1(unsigned x, unsigned y) {
int cmp = (x >= y) - (x <= y);
printf("%u %c %u\n", x, "<=>"[cmp + 1], y);
}
Yet since we cannot use various operators, etc., All we need to do is replace >=.
_Bool foo_ge(unsigned x, unsigned y) {
_Bool yeq0 = 1 - (_Bool)y; // y == 0?
_Bool q = (x + yeq0)/(y + yeq0); // Offset both x,y, by yeq0
return q + yeq0;
}
void cmp2(unsigned x, unsigned y) {
int cmp = foo_ge(x,y) - foo_ge(y,x)
printf("%u %c %u\n", x, "<=>"[cmp + 1], y);
}
Heavy use of _Bool credit to #sun qingyao

Not understanding the calculation

I have following C program, and I'm not understanding the output of the following program.
#include <stdio.h>
int main()
{
int a,b, *p1, *p2, x,y,z;
a=12;
b=4;
p1=&a;
p2=&b;
x=*p1 * *p2-6;
y=4* - *p2 / *p1+10;
printf("y=%d", y);
return 0;
}
The output of the program is 9. But what is the meaning of 4*?
What is the meaning of 4*
The * there is the multiplication operator. Only one operand, 4, is shown in that extract. The full multiplication is:
4* - *p2
which is more clearly written as
4 * -(*p2)
Write out the expression, substituting the values. We can ignore x since it is not used. Which leaves us:
y= 4* - *p2 / *p1+10;
And *p2 is b which is 4. And *p1 is a which is 12. So the expression is:
y = 4 * -4 / 12 + 10;
And this evaluates as:
y = ((4 * -4) / 12) + 10;
Which is
y = (-16 / 12) + 10;
Which is
y = -1 + 10;
The spacing in this line might be causing confusion:
y=4* - *p2 / *p1+10;
This is equivalent to:
y = 4 * (-*p2) / *p1 + 10;
but the spacing makes it look like a subtraction.
The code
4* - *p2
means
4 * (-*p2)
So * means simple multiplication here.
Get familiar with the C precedence and associativity table:
The statements will be evaluated like this (parentheses added for clarity):
x = ((*p1) * (*p2)) - 6;
x = ((12) * (4)) - 6
x = (48) - 6
x = 42
y = (4 * (-(*p2)) / (*p1)) + 10;
y = (4 * (-4) / (12)) + 10
y = (-16 / 12) + 10
y = -1 + 10
y = 9

how does "==" operator work in an expression?

#include <stdio.h>
int main()
{
int a = 10, b = 5, c = 5;
int d;
d = b + c == a;
printf("%d", d);
}
In the above code,could any one please explain to me how d = b + c == a works?
Because of operator precedence, it is parsed as
d = ((b + c) == a);
b + c is 10, which is equal to a, so d receives the value of 1, which is how C represents true comparisons.
Based on precedence of operators, binary + has higher precedence than ==. So the statement will be grouped as,
d = ( b + c ) == a;
Which becomes,
d = ( ( b + c ) == a ); // ==> d = ( 10 == 10 );
So, d holds the truth value based on the comparison (b+c) == a which is 1 because in C comparison operators will return 1 for true and 0 for false.
Its works like this
d = (b+c) == a --> (5+5) == 10 ---> 1
Which returns 1
+ operator has higher precedence than ==.So d=b+c==a; parsed as d=((b+c)==a);. b+c is 10.
so (10==a) evaluates true .So d=1;

Resources