user3787309
user3787309

Reputation: 109

C prog error: expected expression before int

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'

Upvotes: 0

Views: 2053

Answers (4)

haccks
haccks

Reputation: 106092

The error is because of int(a). Syntactically it is wrong. It should be (int)(a).

Upvotes: 0

M.M
M.M

Reputation: 141628

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.

Upvotes: 2

NPE
NPE

Reputation: 500713

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?

Upvotes: 0

Ed Heal
Ed Heal

Reputation: 60017

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)

Upvotes: 0

Related Questions