This is the program:
#include <stdio.h>
#define round(a) ((a-0.5)<int(a))?int(a):int(a+1)
int main() {
double a = 5.2;
int m = round(a);
printf("%d", m); }
and it shows the error: expected expression before 'int'
round is a name reserved by the standard C library so it is undefined behaviour to call your macro that name (even if you don't include math.h).
Your algorithm could be better expressed like this:
#define my_round(a) ( (int)((a) + 0.5) )
which also has the benefit of only evaluating its argument once.
It would be preferable to use an inline function:
inline int my_round(double d)
{
return d + 0.5;
}
Note that both options cause undefined behaviour if a is outside the bounds of INT_MIN, INT_MAX roughly . If it's in a critical environment you should make your inline function check the bounds of d before doing the conversion to int.
This
#define round(a) ((a-0.5)<int(a))?int(a):int(a+1)
Has the brackets in the wron places
Should be
#define round(a) (((int)((a)-0.5))<(a))?(int)(a):(int)(a+1)
The problem is that int(a) is not valid C.
Redefine your macro as follows:
#define round(a) (((a)-0.5)<(int)(a))?(int)(a):(int)(a+1)
Note that I've also added parentheses around a in (a)-0.5.
P.S. What's the reason for making it a macro and not, say, a function?
The error is because of int(a). Syntactically it is wrong. It should be (int)(a).
Related
Please give me full description....
The first snippet of code has the 'function call' (macro invocation) before the increment operator, and second one has the function call after the increment operator.
#include <stdio.h>
#define square(x) x*x
int main()
{
int a,b=3;
a=square (b)++;
printf("%d%d",a,b);
return 0;
}
output:
124
why is 124 returned here
#include <stdio.h>
#define square(x) x*x
int main()
{
int a,b=3;
a=square (b++);
printf("%d%d",a,b);
return 0;
}
output:
125
and 125 here?
The thing to keep in mind is that macros provide simple substitution of preprocessor tokens. In particular, they may evaluate their arguments more than once, and if not guarded by parentheses, they may produce unintended reassociation.
In the first example, we have
a=square (b)++;
This expands to:
a=b*b++;
This is actually undefined behavior, since the b and b++ are unsequenced, and b++ modifies b. In your case, you are seeing 12 and 4 for a and b, so it would seem that the first value of b is picking up the incremented value, so you're getting 4*3, but you can't count on this behavior. The final value of b is 4 since it is incremented once.
In the second example, we have:
a=square (b++);
This expands to:
a=b++*b++;
This is again undefined behavior. In your case, it appears that you're getting 4*3 (or 3*4), but again, you can't count on this behavior. The final value of b is 5 since it is incremented twice, but this too is undefined behavior.
In addition to Tom's answer, which explains what is happening, here is an example of how you could define a macro for squaring a number safely:
#define SQR(x) ( \
{ \
__auto_type x_ = (x); \
\
x_ * x_; \
} \
)
It only has an appearance of x, and therefore it doesn't evaluate it twice. The copy x_ is used instead. Note that variables created in a macro may conflict with other variables created in the function that calls the macro. To avoid name collisions you use special names that shouldn't be used in normal code such as a trailing _.
With this macro, this:
a = SQR(b++);
will be equivalent to this:
a = SQR(b);
b++;
Warning: This works on some compilers as an extension (GCC for example), but it is not standard C.
Another option, if you want standard C, is to use an inline function. It is ok if you want it to work on just one type (there is _Generic in C11, but I never used it, so no idea).
The program I'm trying to write includes a macro to round a real number to the nearest integer and a function which uses that macro to round an array of real numbers.
Here's the program:
#include <stdio.h>
#define SIZE 256
#define round(N) { return (N >=0)? (int)(N+0.5) : (int)(N-0.5) ; }
void round_array(int a[])
{
int i;
for(i=0; i <SIZE; i++)
{
a[i] = round(a[i]);
}
}
int main()
{
return 0;
}
While compiling, I'm getting these errors:
round.c: In function ���round_array���:
round.c:4:18: error: expected expression before ���{��� token
#define round(N) { return (N >=0)? (int)(N+0.5) : (int)(N-0.5) ; }
^
round.c:11:15: note: in expansion of macro ���round���
a[i] = round(a[i]);
^
round.c: At top level:
Why am I getting these errors and how can I fix them?
Because after preprocessing, your code will look similar to that:
a[i] = { return (a[i] >=0)? (int)(a[i]+0.5) : (int)(a[i]-0.5) ; }
If you like to stick to macro, declare it as:
#define round(N) ((N) >=0)? (int)((N)+0.5) : (int)((N)-0.5)
But this is still not really correct because of int/float mixing. That is however already a different topic.
Like it was told to you in a comment, macros aren't functions. They are a token substitution mechanism. So you do not return from them as you would a function.
#define round(N) (((N) >=0)? (int)((N)+0.5) : (int)((N)-0.5))
The changes I made include:
Making it an expression. This involves replacing the curly braces with parentheses. This is so you could use the macro almost anywhere you could use a function. Had I left the curly braces it would have been a compound statement.
Wrapping the parameter N in parentheses as well, to make sure operator precedence doesn't come back and bite us.
Macro-replacement is basically what it sounds like, it replaces the macro with the body of the macro, quite literally.
So when you have
a[i] = round(a[i]);
It will be replaced by
a[i] = { return (a[i] >=0)? (int)(a[i]+0.5) : (int)(a[i]-0.5) ; };
That's not valid syntax. The right-hand side of an assignment must be an expression and not a statement.
A simple solution is to turn round from a macro to an actual function. An even simpler solution is to realize that int values (a[i] is an int) doesn't have fractions, so there's nothing to round.
If you want to use floating-point values though, the correct solution is to use the standard round function, not to make up your own.
If you insist on writing this yourself, you should replace the icky macro with a safer, cleaner function:
inline int int_round (double d)
{
return (int) ( d >= 0 ? d+0.5 : d-0.5 );
}
This should yield the very same machine code.
You don't need the return keyword, it's not a function. Get rid of it.
Quoting C11, chapter §6.8.6.4
A return statement terminates execution of the current function and returns control to
its caller. [...]
which is not the purpose of your MACRO definition. Inclusion of return keyword is unwanted and invalid syntax there.
What you probably want is a syntax like
(N >=0)? (int)(N+0.5) : (int)(N-0.5)
or, something better
( (N) >=0)? (int)((N)+0.5) : (int)((N)-0.5)
without the return and maybe the trailing ; also.
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.
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!