Here is what i have and I wonder how this works and what it actually does.
#define NUM 5
#define FTIMES(x)(x*5)
int main(void) {
int j = 1;
printf("%d %d\n", FTIMES(j+5), FTIMES((j+5)));
}
It produces two integers: 26 and 30.
How does it do that?
The reason this happens is because your macro expands the print to:
printf("%d %d\n", j+5*5, (j+5)*5);
Meaning:
1+5*5 and (1+5)*5
Since it hasn't been mentioned yet, the way to fix this problem is to do the following:
#define FTIMES(x) ((x)*5)
The parentheses around x in the macro expansion prevent the operator associativity problem.
define is just a string substitution.
The answer to your question after that is order of operations:
FTIMES(j+5) = 1+5*5 = 26
FTIMES((j+5)) = (1+5)*5 = 30
The compiler pre-process simply does a substitution of FTIMES wherever it sees it, and then compiles the code. So in reality, the code that the compiler sees is this:
#define NUM 5
#define FTIMES(x)(x*5)
int main(void)
{
int j = 1;
printf("%d %d\n", j+5*5,(j+5)*5);
}
Then, taking operator preference into account, you can see why you get 26 and 30.
And if you want to fix it:
#define FTIMES(x) ((x) * 5)
the preprocessor substitutes all NUM ocurrences in the code with 5, and all the FTIMES(x) with x * 5. The compiler then compiles the code.
Its just text substitution.
Order of operations.
FTIMES(j+5) where j=1 evaluates to:
1+5*5
Which is:
25+1
=26
By making FTIMES((j+5)) you've changed it to:
(1+5)*5
6*5
30
Related
#include<stdio.h>
#define MUL( a, b) a##b
int main( )
{
//static int a = 5;
// while( --a )
printf("%d",MUL(2+3,4+5));
//{
// printf("%d ",a);
// main(10);
//}
return 0;
}
OUTPUT: 41
why the output of the program is 41?
I am using token pasting operator that should merge the two numbers.
I am expecting the output as 59 but its showing 41.
When a macro is expanded, the two tokens on either side of each ‘##’ operator are combined into a single token. Expressions are not evaluated and passed to the macro.
In this case the expansion would be 2+3 ## 4+5 i.e 2 + 34 + 5 = 41.
After replacement it will look like
printf("%d", 2+34+5) ); // 2+34+5 = 41
It will never print 28.
The argument to MUL will not evaluate before the replacement.
MUL(2+3,4+5)
will expand to
2+3##4+5
which is
2+34+5
It evaluates to 41.
To get 59, you need to call MUL(5,9). For even MUL((2+3),(4+5)), preprocessing will be done first which will make it to
(2+3)(4+5)
and will result in compiler error.
MACROs are replaced before compilation phase.
#include<stdio.h>
#include<stdlib.h>
#define d 10+10
int main()
{
printf("%d",d*d);
return 0;
}
I am new to the concept of macros.I found the output for the above program to be 120.What is the logic behind it?
Thanks.
10+10*10+10 == 10 + 100 + 10
Is that clear?
Macros are replaced literally. Think of search/replace. The compiler sees your code as 10+10*10+10.
It is common practice to enclose macro replacement texts in parentheses for that reason:
#define d (10 + 10)
This is even more important when your macro is a function-like macro:
#define SQ(x) ((x) * (x))
Think of SQ(a + b)...
d*d expands into 10+10*10+10. Multiplication comes before addition, so 10 + 100 + 10 = 120.
In general, #define expressions should always be parenthesized: #define d (10+10)
A macro is a nothing more than a simple text replacement, so your line:
printf("%d",d*d);
becomes
printf("%d",10+10*10+10);
You could use a const variable for more reliable behaviour:
const int d = 10+10;
The macro is expanded as is.
Your program becomes
/* declarations and definitions from headers */
int main()
{
printf("%d",10+10*10+10);
return 0;
}
and the calculation is interpreted as
10 + (10 * 10) + 10
Always use parenthesis around macros (and their arguments when you have them)
#define d (10 + 10)
#define
preprocessor directive substitute the first element with the second element.
Just like a "find and replace"
I'm not sure about #include but in C# #define is used at the top to define a symbol. This allows the coder to do things like
#define DEBUG
string connStr = "myProductionDatabase";
#if DEBUG
connStr = "myTestDatabase"
#edif
10+10*10+10 = 20 + 100 = 120
Simple math ;)
Macro doesn't evaluate the value (it doesn't add 10 + 10) but simply replaces all it's occurences with the specified expression.
my code is:-
#include<stdio.h>
#include<conio.h>
#define sq(x) x*x*x
void main()
{
printf("Cube is : %d.",sq(6+5));
getch();
}
The output is:-
Cube is : 71.
now please help me out that why the output is 71 and not 1331...
thank you in advance.
Always shield your macro arguments with parenthesis:
#define sq(x) ((x) * (x) * (x))
Consider the evaluation without the parenthesis:
6 + 5 * 6 + 5 * 6 + 5
And recall that * has a higher precedence than +, so this is:
6 + 30 + 30 + 5 = 71;
Get to know the precedence rules if you don't already: http://en.cppreference.com/w/cpp/language/operator_precedence
You need parentheses around the argument.
#define sq(x) ((x)*(x)*(x))
Without the parentheses, the expression will expand to:
6+5*6+5*6+5
Which you can see why it would evaluate to 71.
A safer solution would be to use an inline function instead. But, you would need to define a different one for each type. It might also be more clear to rename the macro.
static inline int cube_int (int x) { return x*x*x; }
If you define the macro like this:
#define sq(x) x*x*x
And call it:
sq(6+5);
The pre-processor will generate this code:
6+5*6+5*6+5
Which is, due to operator precedence, equivalent to:
6+(5*6)+(5*6)+5
That's why, the macro arguments must be parenthesized:
#define sq(x) (x)*(x)*(x)
So that pre-processor output becomes:
(6+5)*(6+5)*(6+5)
However, if you pass some arguments with side-effects such as (i++):
sq(i++)
It will be expanded to:
(i++)*(i++)*(i++)
So, be careful, perhaps you need a function
#include<stdio.h>
#include<conio.h>
#define PROD(x) (x*x)
void main()
{
clrscr();
int p=3,k;
k=PROD(p+1); //here i think value 3+1=4 would be passed to macro
printf("\n%d",k);
getch();
}
In my opinion, the output should be 16, but I get 7.
Can anyone please tell me why?
Macros are expanded, they don't have values passed to them. Have look what your macro expands to in the statement that assigns to k.
k=(p+1*p+1);
Prefer functions to macros, if you have to use a macro the minimum you should do is to fully parenthesise the parameters. Note that even this has potential surprises if users use it with expressions that have side effects.
#define PROD(x) ((x)*(x))
The preprocessor expands PROD(p+1) as follows:
k = (p+1*p+1);
With p=3, this gives: 3+1*3+1 = 7.
You should have written your #define as follows:
#define PROD(x) ((x)*(x))
The problem here is that PROD is a macro and will not behave exactly like you intend it to. Hence, it will look like this:
k = p+1*p+1
Which of course means you have:
k = 3+1*3+1 = 7
#define PROD(x) (x*x)
PROD(3+1) is changed by the preprocessor to 3+1*3+1
macro are not function . These are replaced by name
It will be p+1*p+1
This is what compiler is going to see after preprocessors does its job: k= p+1*p+1. When p = 3, this is evaluated as k = 3+(1*3)+1. Hence 7.
This is exactly why you should use functions instead of macros. A function only evaluates each parameter once. Why not try
int prod(int x)
{ return x * x; }
and see the difference!
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j;
j = a(i + 1);
printf("%d", j);
return 0;
}
I want to know why the program is not giving the output 16. (I'm getting the output 7.)
I understood the point very much but if the program is like this:
#include<stdio.h>
#define a(x) (x * x)
int main()
{
int i = 3, j, k;
j = a(i++);
k = a(++i);
printf("%d\n%d", j, k);
return 0;
}
Then why does the above program give the following output:
9
49
Because you made a bad macro:
a(i + 1)
expands to
i + 1 * i + 1
which is equivalent to
i + i + 1
or
2 * i + 1
Use parenthesis:
#define a(x) ((x) * (x))
And then you'll get it to expand to
(i + 1) * (i + 1)
which does what you want.
Read up on C operator precedence and think about what the macro a expands to in this case.
After preprocessing the line
j=a(i+1);
will be:
j=(i+1*i+1);
which when evaluated for i=3 will give j=7:
j=(3+1*3+1);
To get the desired result you need to define the macro as:
#define a(x) ((x)*(x))
which results in:
j=((i+1)*(i+1));
and gives the result 16 when i=3
Because a(i+1) gets preprocessed into (i+1*i+1).
And 3+3+1 = 7.
You might want to use parenthesis around x.
edit: Wow, is this redundant or what. :/
Another write-up for the explanation is at http://en.wikipedia.org/wiki/C_preprocessor#Precedence
Because your macro is wrong. Apparently it works, but the error is more subtle (not quite, but still), as the expanded code has some issues, by not following the expected order of operations.
j = a(i+1) will expand to j = i + 1 * i + 1 which is 7.
If you want to resolve your problem redefine your macro as:
#define a(x) ((x)*(x))
It's good that you've encountered this problem now, and not later. Those type of errors, are sometimes very hard to debug, but now you'll know how to write "professional" macros :).
Because a(i+1) gets preprocessed into (i+1*i+1).
And 3+3+1 = 7.
You might want to use parenthesis around x.
edit: Wow, is this redundant or what. :/
link|flag