some error in output in using macro in C - c

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

Related

How ## operator in macro works?

I was studying some macro operations, and I got this Code and I was unable to figure out how this code is actually working and generates the output? and is there any (i-+) operator that exists or not?
Here is the code
#include<stdio.h>
#define p(a,b) a##b
#define call(x) #x
int main()
{
do{ int i=14,j=3;
printf("%d",p(i-+,+j));
}while(*(call(625)+3));
return 0;
}
Output is 10.
It will be very helpful if you explain it with some examples.
The ## in the macro is the concatenation operator, it glues its operands together. So after the preprocessor is done, that expression will be
i-++j
which of course just means i - (++j), i.e. 14 - 4 which of course is 10.

#define directive in C Giving ambiguous answer [duplicate]

This question already has answers here:
C : #define usage [duplicate]
(3 answers)
Closed 7 years ago.
#include <stdio.h>
#define SQR(x) x*x
int main()
{
printf("%d",225/SQR(15));
return 0;
}
The output to this code is 225. I'm unable to understand as what really is happening here.
If I use #define SQR(x) (x*x) Then it works fine which i get as we are supposed to use parentheses if we have an expression with some operator.
But in the previous case I'm not clear as to what is really happening. Why is the answer 225?
#define macros aren't functions - they are just macros, text replacement. If you take the expression 225/SQR(15) and replace SQR with 15*15, you'll get 225/15*15, and since / and * have the save precedence and are left associative - 255/15*15 = 255.
Macros do substitution only(done before compilation of the code).
Therefore the following line
printf("%d",225/SQR(15));
after substitution will become:
printf("%d",225/15*15);
now this expression evaluates to 225 (basic maths : divide first -> 15*15, then multiply -> 225)
using brackets solves your problem(then it becomes 225/(15*15)).
:)
Notice the steps
1) 225/SQR(15)
2) 225/15*15
Division executed first due to precedence
3) 15*15
4) 225
See #define as a text replacement tool in a text editor; it works the same way (well, almost).
Here are two rules you might want to follow in order to avoid this kind of errors:
When working with macros, always use parentheses for each "variable" given to the macro and for the whole result.
Example:
#define MAX(a, b) ((a) > (b) ? (a) : (b))
When you have an unexpected behavior, use the command line tool cpp (c preprocessor) to see how the macro is actually interpreted.
Example:
$ cpp main.c

use of #define in c

#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.

C program output is confusing

#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!

C #define macros

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

Resources