Output of this program is 64. Can someone explain how? - c

#define sqr(a) a*a
int main()
{
int i;
i = 64 / sqr(4); //answer of this expression is 64.
printf("%d", i);
return 0;
}
In this code the output is 64, and according to the rules, the expression i = 64 / sqr(4) should be solved as i = 64 / 4*4, which gives a result of 4, but the output of the program is 64. Why?

Macros are not evaluated like functions, they are expanded in place. The statement
i = 64 / sqr(4);
expands to
i = 64 / 4*4;
Both of the multiplication and division operators have the same precedence and are left-associative, so the above statement is parsed as
i = (64 / 4) * 4;
Thus, you are multiplying the result of 64 / 4 by 4, rather than dividing 64 by the result of 4 * 4.
They way to avoid precedence and associativity issues with macros like this is to enclose the expansion in parentheses:
#define sqr(a) (a * a)
By itself, though, that’s not sufficient - if you do something like sqr(1+2), that will expand to (1+2*1+2), which evaluates to 5 instead of the expected 9. You also need to parenthesize the argument(s) as well as the overall expression:
#define sqr(a) ((a) * (a))
Now your statement expands to
i = 64 / ((4) * (4));
and will evaluate to what you expect.

I'll try to keep this answer simple:
Macros is a set of code that just get replaced at the time of compilation.
Now, if you replace sqr(4) with 4*4
It becomes something like: 64/4*4.
Now, if you apply basic rule of BODMAS. It gets executed as follows:
64/4= 1616*4= 64 i.e first division with 4 then multiplication with 4 that gives 64

You need to look at the order of operations. Multiplication is done first, so it meant (64 * 4) / 4. Here's an updated version with parenshases around your macro:
#define sqr(a) ((a)*(a))
int main()
{
int i;
i = 64 / sqr(4); //answer of this expression is 4.
printf("%d", i);
return 0;
}

Related

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.

Incorrect multiplication of integers in C

A C-coded S-function in Simulink was showing incorrect behaviour and I have managed to narrow down the problem to an incorrect multiplication of integers.
At the start of the code, I have something like:
#define NRBF 21
#define NRBF1 NRBF+1
Then, in a function in the script I have:
void function_name(SimStruct *S, const int_T a)
{
...
int_T base;
base = a*NRBF1;
printf("%i\t", a);
printf("%i\t", NRBF1);
printf("%i\n", base);
..
}
Now, if a=0, NRBF=21, I have (instead of base=0)
0 22 1
If a=1, NRBF=21, I have (as expected base=22)
1 22 22
If a=2, NRBF=21, I have (instead of base=44)
2 22 43
Now, I must say I am a bit baffled. I tried to change the line of the multiplication to
base = a* (int_T)NRBF1;
but it does not solve the problem.
Any help would be greatly appreciated! Thank you!
The problem is here:
You define your macros like this:
#define NRBF 21
#define NRBF1 NRBF+1
When you write this:
base = a*NRBF1;
The preprocessor replaces NRBF1 textually with 21+1 which results in this:
base = a*21+1;
but you intended this:
base = a*(21+1);
Therefore you need to define your macro like this:
#define NRBF1 (NRBF+1)
With the macro expanded, the line looks like:
base = a*NRBF+1;
For a equal to 0, the expression is 0 * 21 + 1 which is 1.
For a equal to 2, the expression is 2 * 21 + 1 which is 43.
The solution is to put parentheses in the macro definition:
#define NRBF1 (NRBF + 1)
This is a good rule for any macro with an expression as its right-hand side.
Remember that macros are just text-substituted into the code.
It's basically calculating alright
0*21+1 = 1
The macro is expanded but the * has precedence over +. That's why this happens.
A more detail explanation would be
#define NRBF 21
#define NRBF1 NRBF+1
So what is going on
base = a*NRBF1;
or
base = a*NRBF+1
Now when a = 0 then base = 1
when a = 1 then base = 21+1 ...so on.
Correct way would be to wrap it aropund parentheses.
#define NRBF1 (NRBF+1)
Some more pitfalls:
That when you add a macro like this #define SQR(X) X*X
For some example like this where same precedence operators are there next to next then it will be problematic.
int i = 100/SQR(10);
Then it will be expanded to
int i = 100/10*10
Now same precedence operators are here executed left to right.
So it will result in i=100.
Solution same #define SQR(X) (X*X)
Also when passing an expression like this SQR(i+1) then it will be expanded to i+1*i+1=2*i+1. So a bit more correct would be
#define SQR(X) ((X)*(X))
Even with that you wouldn't be able to avoid few things if you forget one thing macro just expands - it does nothing more.
You can't use macro like this
SQR(i++) which will be expanded to ((i++)*(i++)). So you are increasing the i twice which is what you didn't mean. Moreover this will result in undefined behavior.
the define doesn't create a single value 22 but the expression 21 + 1. I wonder whether your problems go away if you change your second #define to
#define NBRF1 (NBRF + 1)

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

Output of a C program

I have written the following C program. The output is 32. Why is this?
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define max 10+2
int main(){
int i;
i = max * max;
printf("\n%d\n",i);
return 0;
}
(I am learning C and am relatively new to it.)
#define max 10+2
This is the preprocessor. it is not smart.
it is stupid.
it just replaces text.
max*max
will resolve to
10+2*10+2
which is
10+(2*10)+2
because of operator precedence, which is
10 + 20 + 2
i.e. 32
Furthermore, you should avoid preprocessor macros whenever you can and use static const instead. You may or may not want to also consider using a const variable or an enum instead of a #define; each have their tradeoffs, refer to the similar question: "static const" vs "#define" vs "enum".
If you want to stick to preprocessor, then you could just use:
#define max (10+2)
Since parenthesised code will take operator precendence.
Since max is a macro, it gets expanded textually, so your code comes out with:
i = 10 +2 * 10 + 2;
For a macro like this, you generally want to add parentheses:
#define max (10+2)
So your expression will expand to:
i = (10+2) * (10+2);
The compiler sees this
i = 10 + 2*10 +2 = 32
You should do the macro definition like this
#define max (10+2)
Operator precedence is a funny thing. PEMDAS = Parenthises, Exponents, Multiply, Divide, Add, Subtract.
This is going to resolve to equal to 10 + (2 * 10) + 2.
First is 10*2 which equals 20.
Now it reads 10 + 20 + 2.
The rest should be clear.
You should exercise control over your arithmetics whenever desired.

Using macro results in incorrect output when used as part of a larger math expression - why does this happen?

This is a normal C routine program which i found out in some question bank. It is shown below:
#define CUBE(p) p*p*p
main()
{
int k;
k = 27 / CUBE(3);
printf("%d", k);
}
As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing and after the subsequent compilation it would be giving the value of 1, but instead it has shown the value of 81 which has made me curious to know how it happened.
Can anyone please justify the answer of 81 to this question above.
The preprocessor merely substitutes
CUBE(3)
with
3*3*3
So you end up with:
k=27/3*3*3
Which, evaluated left-to-right with operator precedence, is in fact 81.
If you add parenthesees around the macro, you should find the results are correct:
#define CUBE(p) (p*p*p)
It would be even better to surround each instance of p with parenthesees as well, as in:
#define CUBE(p) ((p)*(p)*(p))
Which will allow you to pass expressions to the macro correctly (for example, 1 + 2).
Because of operator precedence 27/3*3*3 = 81
You could use instead:
inline int cube(int p) { return p*p*p; }
Preprocessors should be parenthesized properly. Replace it with
#define CUBE(p) ((p)*(p)*(p))
and see.
C macros do textual substitution (i.e. it's equivalent to copying and pasting code). So your code goes from:
k=27/CUBE(3);
to
k=27/3*3*3;
Division and multiplication have the same precedence and have left-to-right associativity, so this is parsed as:
k=((27/3)*3)*3;
which is 9 * 3 * 3 = 81.
This is why C macros should always be defined with liberal use of parentheses:
#define CUBE(p) ((p) * (p) * (p))
For more information, see http://c-faq.com/cpp/safemacros.html from the comp.lang.c FAQ.
Your macro is not protected. Try
#define CUBE(p) ((p)*(p)*(p))
The current macro was expanded to
k=27/3*3*3
which is ((27/3)*3)*3
Because macros are a textual substitution, that works out to:
k = 27 / 3 * 3 * 3;
Since multiplication and division happen left to right, that works out to:
k = ((27 / 3) * 3) * 3;
So, you want to change that in two ways:
#define CUBE(p) ((p)*(p)*(p))
The outer parentheses cause the multiplications to be done before any other operations.
The parentheses around the individual p's are for the case where you do:
CUBE(1 + 2);
Without those inner parentheses, operator precedence will trip you up.
k=27/CUBE(3); => k=27/3 * 3 * 3;
Do you see it? CUBE should be defined like this instead:
#define CUBE(p) ((p)*(p)*(p))
When you do macros, you have to be careful about how you place parentheses. In this case, you don't have any, so the expression becomes 27/3*3*3, which by the precedence rules of / and * becomes (27/3)*3*3.
27/3*3*3 = 9*3*3 = 81 ?
Both / and * operators have the same precedence. To execure 3*3*3 first, you shoudl enclose them in parenthesis.
#include <stdio.h>
#define CUBE(p) p*p*p
int
main ()
{
int k;
k=27/(CUBE(3));
printf("%d",k);
return 0;
}
#define CUBE(p) p*p*p
main()
{
int k;
k=27/CUBE(3);
printf("%d",k);
}
As per my understanding and knowledge the value of K should be 1 as CUBE(3) would be replaced by 3*3*3 during preprocessing
YES
and after the subsequent compilation it would be giving the value of 1,but instead it has shown the value of 81 which has made me curious to know how it happenned.
NO,
k= 27/3*3*3
=(((27/3)*3)*3) (The precedence of `*` and `/` are same but the associativity is from left to right)
=((9*3)*3) =81
Replace #define CUBE(p) p*p*p with #define CUBE(p) ((p)*(p)*(p))
its the way in which the associativity and precedence of operators is implemented.
when the expression is expanded it becomes
27/3*3*3 and not 27/(3*3*3)
now, division and multiplication both have the same precedence in C but the associativity is left to right for both.
so it can be shown as :
(27/3)*3*3 which in turn equals (9*3)*3 = 81
also, if u remember the old arithmetic rule of BODMAS(Bracket Off Division Multiplication Addition Subtraction), this is the order of precedence, then we do division first and then multiplication.
so again we get answer as 81 for 27/3*3*3.
Hi answer for this is:81
Explanation:
In step k=27/cube(3)
cube(3) is replaced by 3*3*3 by preprocessor.then above statement becomes as k=27/3*3*3
in that 27/3 expression is evaluated by c compiler(operator precedence)
the result is(27/3) :9
the statement k=27/3*3*3 becomes as k=9*3*3;
the result for above statement is 81:

Resources