C program output - c

#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

Related

Why following code doesn't compile?

Hi can't find the mistake in my code.
I'm still newbie in programming. So please don't be so mean to me.
The compiler says:
Line:23 error: expected ')' before ';' token
Line:24 error: expected ';' before ')' token
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
#include <stdbool.h>
#include <time.h>
#include <unistd.h>
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0);
int size=5,location_x=10,location_y=10,s=NULL,l_x, l_y, status=2;
int main(void)
{
srand(time(NULL));
float location[l_x][l_y];
int x[size], y[size], z[size];
l_x=1+rand()%100;
l_y=1+rand()%100;
for (int i=0; i<size; i++){
location[l_x][l_y] += CENTER(x[i], y[i], location_x, location_y, z[i]);
}
return 0;
}
The error message is because the parentheses on your macro are unbalanced:
//opening -> 1 23 45
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0);
//closing -> 1 2 3 4
and can be fixed by simply placing another closing parenthesis after the fourth closing one, assuming the expression is meant to be:
And you really don't want to have a semi-colon on the end of it, a better example would be (but see below):
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0))
The semi-colon is particularly annoying if you use the macro anywhere other than the end of a statement which, luckily, you're not doing, but may well at some point in the future. For example, this construct will fail insidiously with the semicolon:
x = CENTER(1,2,3,4,5)+42;
Insidious since it will compile but won't do what you think it will, for example, the following code will not print out 100:
#include <stdio.h>
#define FN(x) (x);
int main (void) {
int xyzzy = FN(10) + 90;
printf ("%d\n", xyzzy);
return 0;
}
That's because, after pre-processing, you end up with:
int plugh = (10); + 90;
which is actually two valid C statements, the first setting xyzzy to ten, the second evaluating (but throwing away) the expression + 90.
However (and this is the "see below" bit mentioned above), I'd go further and say you probably shouldn't be using a macro here at all. The three main use cases for macros (from the earliest days of C) can generally be divided into:
conditional compilation;
inlining of code; and
constants.
With the second generally being obsolete because of insanely optimising compilers, and the third being less useful than enumerations (unless you want to pass in compile-time configurable constants such as gcc -DUNITS_PER_BIN=42 ...), I'd suggest conditional compilation is the only place you should be using macros nowadays.
Instead, I would simply use the function:
inline float center (float a, float b, float x, float y, float g) {
return g * sqrt (pow ((x - a), 2.0) + pow ((y - b), 2.0);
}
(but with more descriptive variables if possible).
I generally don't even use inline nowadays since the compilers can generally figure it out, but I've put it there for completeness.
This also gets rid of a lot of the problems of function-like macros such as when you pass something like var + 7 as your (unparenthesised) g variable and find out the expression isn't giving you want you wanted because of operator precedence:
var + 7 * sqrt (pow ((x - a), 2.0) + pow ((y - b), 2.0))
when what you really wanted was:
(var + 7) * sqrt (pow ((x - a), 2.0) + pow ((y - b), 2.0))
Perhaps this:
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0);
...needs an extra parenthesis to close the expression, like this:
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0))
You should also remove the trailing semi-colon.
you need one ) at the end of g*sqrt(pow((x-a),2.0)+pow((y-b),2.0);
use
#define CENTER(a,b,x,y,g) g*sqrt(pow((x-a),2.0)+pow((y-b),2.0))
^
And remove ; as well at the end
to create a constant you use the #define, but this statement does not want a ; sign behind it's calcolation. lso you are missing a ) at the end of the statement.

Ununderstandable function-like macro in C

i have this c macro code :
#define d(x, y, z) ( \
x += z, \
y += x, \
x += y \
)
I have several questions :
Does this macro function return something ? (e.g. return x, y, or z)
or is it just add the parameter variable with itself ? (which is
useless, i think).
What does the \ means ?
Why does the original coder use comma-operator after each operation ? Why not just use ; instead of , ?
Any help would be appreciated
Does this macro function return something ? (e.g. return x, y, or z) or is it just add the parameter variable with itself ? (which is useless, i think).
It modifies the value of the variables. The "return" value is the final value of x.
What does the \ means ?
When placed last on a line, it negates the newline so that the macro definition can span more than one line.
Why does the original coder use comma-operator after each operation? Why not just use ; instead of `, ?
Macros replace text. Consider the following code:
int x=1, y=2, z=3, f;
f = 3 * (d(x,y,z));
If the macro uses comma, the code becomes:
int x=1, y=2, z=3, f;
f = 3 * (x+=z, y+=x, x+=y); // Evaluates to 3 * (the final value of x)
If the macro uses semicolon, the code becomes:
int x=1, y=2, z=3, f;
f = 3 * (x+=z; y+=x; x+=y); // Syntax error!!!
1) The macro does not return anything itself. It is just a dumb piece of code substituted literally by the preprocessor wherever it encounters it. It can be any kind of text.
2) \ is used for letting the preprocessor know that the current macro also expands over the next line. (multi-line macro)
3) I cannot make any assumption about the original coder's intentions. However by using the comma operator in there the whole macro becomes a C language expression. For example running something like this works (it wouldn't if semicolons were in there):
int a = 0;
int x = 1;
int y = 2;
int z = 3;
a = d(x, y, z);
printf("a = %d\n", a);
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("z = %d\n", z);
and prints:
a = 10
x = 10
y = 6
z = 3
First and foremost #define is a Preprocessor Directive, which means when the source code/c code is complied the #define replaces LHS with RHS - meaning whereever the d(x,y,z) is used will be replaced with the equation given
for example the below c code will print - modified a = 9, b=8, c=9
#define d(x,y,z) \
x+=1, \
y+=2, \
z+=3
#include <stdio.h>
int main()
{
unsigned int a,b,c;
a=5;
b=6;
c=7;
printf("modified a = %d, b=%d, c=%d \n",d(a,b,c));
}
basically what happened here is d(a,b,c) - is replaced with a+=1,b+=2,c+=3
The meaning of \ is that the pre-processor directive continues in the next line.
As for as the comma-operator is concerned we need to look at source code to see where exactly it is used. as you can see in the above code the comma operator actually separates all the three variables and is able to print properly - if in case i replace comma with any other operator we will get compilation error.
Hope this answers your questions :)
Regards
Hari

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