use of #define in c - 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.

Related

Is there a way to manipulate preprocessor define scope in C

Just curious. Imagine I need to have a #define A that is the sum of n numbers, and those n numbers have a meaning I'd like to make explicit, but only for the computation of A, to improve readiblity,
instead of writing n macros or just writing #define A <result_of_the_sum>.
Is there a way I could limit the reach of these n #define directives to just the definition of A ? Just as in C one would do :
int a = 0;
{
int b = 1;
int c = 2;
int d = 3;
a = b + c + d;
} // end of b,c,d scope.
My intention is to have A defined when compiling but no definition for the other n defines used to compute A, since these would only be useful to understand the code better.
Edit:
Imagine I have these macros:
#define MEANINGFUL_NUMBER_1 1
#define MEANINGFUL_NUMBER_2 2
#define MEANINGFUL_NUMBER_3 3
And I have a macro, A that is the sum of them, and I like someone reading my code to understand the value of A not just see it defined straightforwardly, i.e. #define A (MEANINGFUL_NUMBER_1 + ... + MEANINGFUL_NUMBER_N), such that only A is substituted before compilation but MEANINGUL_NUMBER_* is not.
Is there a way to manipulate preprocessor define scope in C
No.
Is there a way I could limit the reach of these n #define directives to just the definition of A ?
No.
Note that macros are evaulated upon use. That means that everything has to be visible when the macro is used. You can #undef all the macros after all usages, ergo "limit the reach" in that way.
In C, there are no namespaces. In C use prefixes. You would do:
#define LIB_PRIV_B 1
#define LIB_PRIV_C 2
#define LIB_PRIV_D 3
#define LIB_A (LIB_PRIV_B + LIB_PRIV_C + LIB_PRIV_D)
If you really do not want the numbers to leak into C, then use something to generate the C source code, which also gives you more power to the preprocessor side. Use jinja2, m4, php or python, and configure your build system to properly handle the generation dependency.

What does #define, EQ(a, b) ((a) == (b)) mean?

I have this been given C code where the heading statement includes the following:
#define, EQ(a, b) ((a) == (b))
What does it mean?
The comma is an error that will prevent the code from compiling: I'll assume that it's a typo.
Given:
#define EQ(a, b) ((a) == (b))
This defines a macro for the equality operator ==.
Using this macro later in the code, you can type, e.g.:
if (EQ(2+2, 4))
instead of:
if (2+2 == 4)
Not very useful, really.
It means nothing: this code is ill-formed. The token immediately following a #define must be an identifier, which , is not.
If the , were to be removed, this would define a function-like macro named EQ that takes two arguments.
Let's take it step by step
#define MAX 10
This will replace every instance of the word "MAX" by 10 in your code file. this is very much like defining a constant variable with one major difference. The interpretation of #define statement is done way before compilation. which helps for an example to use MAX as an array size. Which would have caused a compiler error in many cases if you have used a variable instead.
you can use cpp <filename.c> command in Linux terminal to see what will happen when a macro is executed.
for an example this code:
#define MAX 10
int numbers[MAX];
after preprocessing (i.e. interpretation of the preprocessor macros)
int numbers[10];
note that the #define statement will vanish once interpreted.
This takes us to another example
#define square(x) (x * x)
every instance of square(x) in our code will not only be replaced by (x * x) but also the value of x will be replaced. Which has an effect similar to function deceleration but again it is different
so
square(5) will be replaced by (5 * 5)
Finally our example
#define, EQ(a, b) ((a) == (b))
This will replace every instance of EQ(a, b) by ((a) == (b))
so for an example
EQ(4, 5) will be replaced by ((4) == (5))
Now what does "==" mean? it is the "check if equal" if 4 and 5 are equal the whole expression would evaluate as 1 (which obviously is not true) and thus this expression will end up to be evaluated as 0.
Which more or less like the effect of this function
int EQ(int a, int b)
{
return (a == b);
}
Which could be also written as
int EQ(int a, int b)
{
if (a ==b) return 1;
if (a !=b) return 0;
}
Note that with the macro we avoided two variable declarations and there is no function call really and it is in general quicker. This advantage will be obvious if you have a slower processor (or microprocessor).
Finally let me state the obvious
#define simple_macro 5
int some_integer_variable = 10;
.
.
.
some_integer_variable = simple_macro;
simple_macro = 12; /* illegal statement */
simple_macro++; /* illegal statement */
because after running the preprocessor this will be
int some_integer_variable = 10;
.
.
.
some_integer_variable = 5;
5 = 12;
5 ++;
Oh! I might have talked too much but let me leave you with this (obvious) code
#define MAX 10
int variable = MAX; /*this is a MAX variable */
char some_string[] = "the MAX value"; /* no replacement will happen here */
int variable_MAX; /* no replacement will happen here */
after running the preprocessor will be
int variable = 10;
char some_string[] = "the MAX value";
int variable_MAX;

some error in output in using macro in 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

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