views:

621

answers:

3

Hi, I'm attempting to use the #define directive to change all of "ulong" to "unsigned long". Here is an example:

#define ulong unsigned long
ulong idCounter = 0;

Sadly, I think it ends up replacing ulong with "unsigned", rather than "unsigned long". I tried "#define ulong (unsigned long)", but that didn't worth either.

+8  A: 

why don't you use just typedef?

typedef unsigned long ulong;
Jack
+2  A: 

Your macro works OK:

cpp ulong.c

gives

# 1 "ulong.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "ulong.c"

unsigned long idCounter = 0;

I originally assumed that you already had a typedef called ulong and were trying to override that with the preprocessor, but other people have a different take on it. If you actually want the ulong, you should use a typedef, as they said.

Kinopiko
+10  A: 

Better use a typedef. The reason your macro may fail is - it might not syntactically valid in some places. Consider:

double x = calc();
ulong v = ulong(x);

In this case, you get

unsigned long v = unsigned long(x);

This is not valid, because the cast form used is not compatible with the way you name the type (it has to consist of a simplier form, like a single word). Use a typedef:

typedef unsigned long ulong;
Johannes Schaub - litb
I understand now; didn't know there was a significant difference. I'll refrain from using #define for substitution like that in the future.
Anthony
Actually, I've never seen a cast done like that - I always do it as (ulong)x, which would work. But, if your syntax is valid (and I have no reason to doubt that, @litb), you raise a good point. +1.
paxdiablo
@paxdiablo, well it's a C++ only feature, C doesn't have this cast. It's the only one i can think of that would break here - not sure whether there are other places. For other things, there are other places tho that affect C too: `#define intptr int*` would break for `intptr a, b;` for example. Thanks for your trust, mate :)
Johannes Schaub - litb
Then again, you can't write `ulong long` with a typedef. Not sure whether that proves the superiority of macros, or their inherent evil though ;)
MSalters