PDA

View Full Version : Generic Coding Question


seveianrex
10-23-2008, 06:45 PM
Okay, admittedly I'm a self taught programmer and I never quite understood binary operators.

In working with the "CLASSES" column for AA's I was able to get a grasp on the binary 'AND' (&) operator, and I understand how bitshifting (1 << value) works.


I was curious though... I've seen some very elegant looking code before in terms of something like the following:


switch (GetAA(aaNumberOne) | GetAA(aaNumberTwo))
{
//blah
}


which would utilize the non-zero value.

would the above code work? if aaNum1 returned 0 and aaNum2 returned 3, for example, would it switch (3) ?

just seems a lot more elegant than doing two switches that do the same thing. i realize i could use an integer variable too, but that gets clunky lookin'.

Sildorei
10-24-2008, 12:20 PM
No, it wouldn't work because in a switch you'll only use a code like following :

switch(myvar)

You can't use a binary operator in a switch ( i think).

spoon
10-24-2008, 12:56 PM
Actually it should work because bitwise operations are expressions that return an integral type. An expression doesn't have to be just a variable.

VS2005 switch definition (http://msdn.microsoft.com/en-us/library/k0t5wee3(VS.80).aspx)

And our quick test proves it:


#include <iostream>
using namespace std;

int main() {
int x = 1;
int y = 5;

switch( x | y ){
case 0: printf("0"); break;
case 1: printf("1"); break;
case 2: printf("2"); break;
case 3: printf("3"); break;
case 4: printf("4"); break;
case 5: printf("5"); break;
case 6: printf("6"); break;
case 7: printf("7"); break;
default: printf("other"); break;
}
}


5

Derision
10-24-2008, 01:31 PM
You're fine if one of the two operands is always zero, but you may get strange results if both are non-zero, e.g. 1 | 3 = 3, 1 | 4 = 5.

spoon
10-24-2008, 02:32 PM
I would bet he is asking because of the duplicate AAs (http://www.eqemulator.net/forums/showthread.php?t=26598) where one would always be 0.

However, I don't think this is a "elegant" solution, but a clever one. Clever meaning buggy and hard to maintain. At this level of abstraction, we are dealing with int32s and not bits or bitmasks. You could do something like:

int32 aaValue = ( GetAA(aaNumberOne) > GetAA(aaNumberTwo) ) ? GetAA(aaNumberOne) : GetAA(aaNumberTwo);

case(aaValue) {
... snip ...

if you wanted to be clever, but still maintain the proper level of abstraction. However I would write the extra couple lines and maybe add a comment just to let the maintainer know whats going on.

I tend to follow the KISS principle (Keep It Simple Stupid)

spoon
10-24-2008, 02:41 PM
case(aaValue) {




switch(aaValue) {