desktop wrote:
Shadowman wrote:
>desktop wrote:
>>I have a function that increments x:
void fun(int arg) {
int x = 10;
x++;
}
is there someway to change 'x++' to 'x--' based on the argument
'arg'. Or do I have to make an if statement?
void fun(int arg) { int x = 10; x += arg; }
fun(1); //increment
fun(-1); //decrement
or
void fun(int arg) {
int x = 10;
switch(arg) {
case 0:
x++;
break;
case 1:
x--;
}
}
fun(0); //inc
fun(1); //dec
But what's wrong with an if?
The problem is that I have that conditional in a loop that potentially
gets executed many times. So it would be nice if it was possible to
make the test once before the loop.
if (arg == 1) {
somevar = x++;
} else {
somevar = x--;
}
while (running) {
somevar;
}
Are you optimizing prematurely? How much improvement do you really
expect from eliminating a single 'if'?
Now, to get dir of the 'if' entirely you _could_ (does not mean that
you should) duplicate the 'while' and do
if (arg == 1) {
while (running) {
...
++x;
...
}
}
else {
while (running) {
...
--x;
...
}
}
Or even extract it into two separate functions. Once you do that,
you can actually compare the performance with the code that has
the 'if' in it. Unless the '...' in my example represent almost no
code, the difference is going to be single percent points. In my
book it's usually not worth the headache of maintaining duplicated
code.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask