#define function gives me unexpected result [duplicate] - c

This question already has answers here:
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 6 years ago.
I defined a function using #define, but when I print out a simple result of an operation it gives me an unexpected result. Here is the code:
#include <stdio.h>
#define CUBE(x) (x * x * x)
int main() {
int m, n = 3;
m = CUBE(n + 1);
printf("%d %d", m, n--);
return 0;
}
The result printed is 10 and 3 and I can't understand why. Since it multiplies n by itself 3 times, and then adds 1, shouldn't the result be 28 and 3?

You don't #define functions, you #define macros, and those are quite different from functions.
They aren't called. They are expanded into the source code directly by the preprocessor, before the code is compiled by the compiler.
They have pitfalls that one must be aware of. To name one, if you pass an expression with side effects to a macro the uses its parameter more than once, the side effects will occur more than once, and you may get wrong results.
The substation is plain token substitution, so
CUBE(n + 1)
will be expand to this:
(n + 1 * n + 1 * n + 1)

#define CUBE(x) ((x) * (x) * (x))
should give you the expected result.
In your, on preprocessing, x in CUBE(x) is replaced by 3+1 which gives you
(3+1 * 3+1 * 3+1) // this happens during pre-processing, not in run time
as macro is plain-text replacement.
which will be grouped like
(3+(1 * 3)+(1 * 3)+1)
giving you 10. For more complex cases, I suggest writing a function.

As the previous answer already suggest, you are missing a pair of brackets,
because the preprocessor basically does find and replace. So your version result in
m = n + 1 * n + 1 * n + 1
which evaluates to the result, you observed.
With
#define CUBE(x) ((x) * (x) * (x))
you will get the correct calculation of
m = (n + 1) * (n + 1) * (n + 1)

Related

Why is the output 16? (C pogramming) [duplicate]

This question already has answers here:
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 2 years ago.
#include<stdio.h>
#define sqr(x) x*x
int main()
{
int a = 16/sqr(4);
printf("%d", a);
}
if I am not wrong the output should be 1
as ,a = 16/sqr(4) gives 16/16 => 1
but the output is 16
this is happening only when I take division operator(/) ,I am getting correct output when using other operators
may I know the reason? .. and thank you
16 / 4 * 4 is (16 / 4) * 4 = 16
Moral: always take care with macros. In your case you should enclose in parenthesis:
#define sqr(x) ((x)*(x))
There are still problems with this macro as it evaluates the argument twice.
For instance:
int read_int();
int a = 16 / sqr(read_int());
Will unexpectedly evaluate read_int() twice as it expands to:
int a = 16 / ((read_int() * (read_int());
The advice would be to use functions for this. Make it inline to give the compiler better chances to optimize it.
a = 16/sqr(4);
Expanded the above expression gives:
a = 16 / 4 * 4
Which is 16 based on normal mathematical order of operations.
That's why macros should always be enclosed in parentheses:
#define sqr(x) ((x) * (x))
Are you trying to make a function definiton? If yes, then i don't think it should be on a #define. Instead, make a function sqr(x). Here's how:
#include <stdio.h>
int sqr(int x)
{
return x*x;
}
int main()
{
int a = 16/sqr(4);
printf("%d", a);
}
And you'll get the result 1.
Edit: but anyway, you've already get the solution with macros. This is just another way to do what you want.

Is there any difference between this two macros? [duplicate]

This question already has answers here:
C macros and use of arguments in parentheses
(2 answers)
The need for parentheses in macros in C [duplicate]
(8 answers)
Closed 3 years ago.
I find no difference between these two macros except the parentheses surrounding the macro in the first one.
Is it a matter of readability or is it a way to deal with the priority of operators?
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)
Yes, there is a difference. The parentheses are needed so that the result of the macro is evaluated as a single expression, rather than being mixed with the surrounding context where the macro is used.
The output of this program:
#include <stdio.h>
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*a))
#define TAM_ARRAY2(a) sizeof(a)/sizeof(*a)
int main(void)
{
int x[4];
printf("%zu\n", 13 % TAM_ARRAY (x));
printf("%zu\n", 13 % TAM_ARRAY2(x));
}
is, in a C implementation where int is four bytes:
1
3
because:
13 % TAM_ARRAY (x) is replaced by 13 % (sizeof(x)/sizeof(*x)), which groups to 13 % (sizeof(x) / sizeof(*x)), which evaluates to 13 % (16 / 4), then 13 % 4, then 1.
13 % TAM_ARRAY2(x) is replaced by 13 % sizeof(x)/sizeof(*x), which groups to (13 % sizeof(x)) / sizeof(*x), which evaluates to (13 % 16) / 4, then 13 / 4, then 3.
Along these lines, TAM_ARRAY would be better to include parentheses around the second instance of a as well:
#define TAM_ARRAY(a) (sizeof(a)/sizeof(*(a)))
Macros are replaced textually in an early phase of code translation. Unless side effects are specifically expected, it is very important to fully parenthesize macro arguments in the macro expansion and the macro expansion itself if it is an expression.
In the case posted, you are unlikely to have a problem because few operators have higher precedence and they would probably not be used around the macro expansion, but here is a pathological example:
TAM_ARRAY(a)["abcd"] expands to (sizeof(a)/sizeof(*a))["abcd"] whereas
TAM_ARRAY2(a)["abcd"] expands to sizeof(a)/sizeof(*a)["abcd"] which is equivalent to sizeof(a) / (sizeof(*a)["abcd"]).
Note however that an operator with the same precedence placed before the macro expansion such as % would definitely cause problems as explained in Eric Postpischil's answer.
Note also that a should be parenthesized too:
#define TAM_ARRAY(a) (sizeof(a) / sizeof(*(a)))
The way macros work is that the code is "swapped out" when compiling.
So something like
#define ADD(i, j) i + j
int k = ADD(1, 2) * 3
would be seen as: int k = 1 + (2 * 3)
Whereas,
#define ADD(i, j) (i + j)
int k = ADD(1, 2) * 3
would be seen as: int k = (1 + 2) * 3
So, there are two macros likely because of operator priority.

Using #define in c for equations

Can someone explain to me why the value of y here is 13?
#include <stdio.h>
#define avg_sum(n) n * (n-1)/2
int main(){
int y;
int z = 9;
y = avg_sum(z+1);
printf("y=%i\n",y);
}
avg_sum(9+1) 9+1 * (9+1-1)/2 = 9 + 9/2 = 9+ 4 = 13
macros expand each time so 9+1 is not the same as 10, it might be better with safeguarding parenthesis as follows:
#define avg_sum(n) ((n) * ((n)-1)/2)
but an equivelant function will do you much better and be more intuitive and will evaluate arguments only once
avg_sum(a++) will be ((a++) * ((a++)-1)/2) and will increment a twice whereas a function will not have these issues since all arguments are evaulated before the function is called
The best way to answer these sorts of questions is to simply expand the macro in question:
y = avg_sum(z+1);
y = z + 1 * (z + 1 - 1) / 2
y = 9 + 1 * (9 + 1 - 1) / 2
y == 13
This is why you add parentheses around your macro arguments.
#define avg_sum(n) ((n) * ((n)-1)/2)
y = avg_sum(z+1);
expands to z + 1 * (z+1-1)/2 but it's wrong. Change your macro to
#define avg_sum(n) ((n) * ((n)-1)/2)
And always parenthesize as well arguments of functional macros as the macro itself . It's an important rule.

Why doesn't this math work with macros? [duplicate]

This question already has answers here:
some error in output in using macro in C
(3 answers)
Closed 9 years ago.
Why doesn't this math work with macros in C?
#include <stdio.h>
#define FOO 6
#define BAR 32
#define MULT FOO * BAR
main() {
int x = 28296;
int y = x / MULT;
printf("%d / %d = %d\n", x, MULT, y);
return 0;
}
The result of this is:
28296 / 192 = 150912
Why isn't it 147? If I set a variable " int mult" equal to MULT, and use the variable in the expression (int y = x / mult) it works as expected.
#define tells the preprocessor to replace the code before compilation, so your line actually says:
int y = x / 6 * 32;
since * and / operators have the same precedence, and are evaluated from left to right, you get (x/6) * 32. The compiler would probably do this calculation for you since x is known to it.
Instead, use parenthesis when defining macros like this
Put a bracket around the macro:
#define MULT (FOO * BAR)
Now, you'll get 147.
The reason getting 150912 is that after macro expansion the expression is equivalent to:
y = 28296 / 6 * 32;
and hence it's evaluated as 28296/6 and then multiplied by32.
As #kevin points out, it's better to put brackets around FOO and BAR as well in general case to avoid surprises like this.

C Macro Behavior

I have the simple following C code
#define Sqrt(A) A * A
int main(void) {
int A = 10;
int x = Sqrt(A+1);
return 0;
}
For some reason, when I used it like that, with A+1, I get x to be 21, which is probably 10+11.
My question is, how is the multiplication is being ignored?
If I switch the macro with the macro text, I get the right result which is 121.
Thanks.
First, your Sqrt is misnamed, should be Square (not square root)
Then, generate the preprocessed form (i.e. with gcc -C -E) and look inside it.
#define Sqr(A) A * A
int a = 10;
int x = Sqr(a+1);
where the last line is expanded as
int x = a+1 * a+1;
Which is parsed as
int x = a+(1*a)+1;
Moral of the story, always use extra parenthesis in macro definition, i.e.
#define Sqr(A) ((A)*(A))
Even with such a definition, Sqr(a++) is probably undefined behavior and at least is naughty.
So you want to avoid macros and actually, learn to use inline functions like
inline int square(int a) { return a*a; };
BTW, you will want to make it static inline not just inline (and put that in a header file)
'cos
#define Sqrt(A) A * A
makes
Sqrt(A+1);
translate to
A + 1 * A + 1
and A is 10
so you get
10 + 1 * 10 + 1
Now do the maths!
BTW sqrt has seems to say square root not squared!
You define the macro as A * A. So, Sqrt(A + 1) expands to A + 1 * A + 1, which is, due to operator precedence, equal to 2 * A + 1 - you've got 2 * 10 + 1 = 21.
That's why you should always parenthesize your macros and their arguments:
#define Sqrt(A) ((A) * (A))
By the way, why a macro? What if one day you write Sqrt(A++)? Then you can expect nasal demons. It would be safer to write an inline function instead (horribile dictu, a correctly named inline function):
static inline double square(double x)
{
return x * x;
}
Inside the macro, A is replaced with whatever was passed into the macro invocation. In this case, that is A+1. This means that the macro gets expanded to:
A+1 * A+1
Due to operator precedence, this is interpreted as A + 1*A + 1, or 10 + 10 + 1 = 21.
You should define the macro as #define Sqrt(A) ((A) * (A))
BODMAS rule buddy!! as the previous answers suggests. Multiplication takes place before your addition.
Your opertaion Sqrt(A+1) where A = 10 will evaulate to 10+1*10+1
10+10+1
21!!
Macros are substituted literally and then evaluated.
Since multiplication has more priority than addition, when you give A+1 to the macro it becomes 10 + 1 * 10 + 1 => 10 + 10 + 1 => 21
Likewise if you give A+2 ..... 10 + 2 * 10 + 2 => 10 + 20 + 2 => 32.
when you call x = MACRO_NAME(A+1); this statement is replace as x = A + 1 * A + 1
in c priority of multiplication is more than addition so it will be 1st executed 1*A which give as A, then A+A+1 will give you result as 21`enter code here`
i.e A+1*A+1
= A+A+1
= 21
for proper answer you need to write Macro as #define MACRO_NAME(A) (A) * (A) which give you result as
121

Resources