Nocturnal
Nocturnal

Reputation: 683

Problem with definition in C++ under VS2010

Been working on some code and thought it would be a bit clever to try and implement some fast workaround define functions. Yet everything turned upset down when I decided to factor MostSigBit function in a single define and suddenly building my project started failing.

Even rewrote this code using if-else statements, no luck still stuck with same results!

#define MostSigBit(x)   (x&0x80 == 0x80) (x = x<<1 ^ 0x1B) : (x <<= 1)
#define MultiplyBy2(x)  (x != 0) ? (MostSigBit(x)) : 0
#define MultiplyBy3(x)  (x != 0) ? (MostSigBit(x) ^ x) : 0

Upvotes: 0

Views: 233

Answers (2)

Pawel Zubrycki
Pawel Zubrycki

Reputation: 2713

Parentheses missing, should be:

#define MostSigBit(x)   (((x) & 0x80 == 0x80) ? ((x) = ((x)<<1 ^ 0x1B)) : ((x) <<= 1))
#define MultiplyBy2(x)  (((x) != 0) ? (MostSigBit(x)) : 0)
#define MultiplyBy3(x)  (((x) != 0) ? (MostSigBit(x) ^ (x)) : 0)

Consider using inline functions for that, as Frederic wrote macros are evil:

inline char MostSigBit(char x) { return (x & 0x80 == 0x80) ? (x<<1 ^ 0x1B) : (x << 1); }
inline char MultiplyBy2(char x) { return x != 0 ? MostSigBit(x) : 0; }
inline char MultiplyBy3(char x) { return x != 0 ? MostSigBit(x) ^ x : 0; }

Upvotes: 3

Loghorn
Loghorn

Reputation: 2807

A question mark is missing:

#define MostSigBit(x)   (x&0x80 == 0x80) (x = x<<1 ^ 0x1B) : (x <<= 1)

should be:

#define MostSigBit(x)   (x&0x80 == 0x80) ? (x = x<<1 ^ 0x1B) : (x <<= 1)

Upvotes: 1

Related Questions