开发者

Multiple condition clause in C/ C++

My aim is to get two numbers and perform an corresponding to the values they hold:

For ex.. Let the vars be x and y.

I need to compute the value of another var z, as follows:

z = x + y // if x = y = 1

z = x - y // if x = 0 and y = 1

Since开发者_Go百科 i need to use it several times, it would not be efficient to use if else within a loop.

What i basically require is like a macro.... preferably using #define., like if it were to be used once:

#define x + y 1 replaces x+y with 1, but does not depend on the values of x and/or y

Is there any way I could replace x+y with 1, x-y with 0 and so on...


You cannot know the values of x and y until runtime, so there is nothing you can do but use an if like you were going to and think of the math that will require the fewest operations (taking into account that 1 = subtraction = addition < multiplication < division usually).

If I misunderstood and you simply want to replace x + y with 1 and x - y with 0, you can just replace them by hand or via find and replace.


If the vars are integers/any other primitive type you can't improve the performance, since the compile will usually translate it one assembly code line. such as sub eax, ebx

Anyhow, as mentioned before, you can't do it on compile time since x,y values are not known at compile time.

you can hint the compiler to save x and y on a register using the register keyword, which will save the variables on the CPU registers in order to preform faster calculations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜