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'

Answers


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


Need Your Help

F#, namespaces, modules, fs and fsx

f# namespaces module projects-and-solutions f#-interactive

I'm aware of other questions about modules and namespaces in F#, but they're not helping me right now.