## Sunday, July 16, 2006

### C/C++ questions .. tricks

Exchange two numbers without using a temporary variable.
B = A XOR B;
A = A XOR B;
B = A XOR B;
x ^= y; y ^= x; x ^= y;

or
x ^= y ^= x ^= y;

Print 1-100 without if or loop
void print(int x)
{
double i = 1/(101-x);
printf("%i ", x);
print(x+1);
}
int main()
{
try{ print(1); }
catch(...){}
}
My trick: (Dr. Diez)
if (a>7) a=7;

re-write:
t = -(a>7);
a = ((t&7) | ((~t)&a));

Multiply by 7 without useing *
x = (x << 3) - x

Convert Dec. integer number to Binary without loop (recursion)
void printbits(int x)
{
int n=x%2;
if(x>=2)
printbits(x/2);
printf("%d", n);
}

What is the difference between define and typedef
Defines are handled by a preprocessor, Typedef is handled by a c compiler itself.
typedef int MYINT, we can use int a or MYINT a; but cannot declare unsigned MYINT a, unsigned int a works.
#define SPRING 0
#define SUMMER 1
#define FALL 2
#define WINTER 3

An alternate approach using enum would be
enum { SPRING, SUMMER, FALL, WINTER };
enum MyEnumType { ALPHA, BETA, GAMMA };

ALPHA has a value of 0, BETA has a value of 1, and GAMMA has a value of 2.
If you want, you may provide explicit values for enum constants, as in
enum FooSize { SMALL = 10, MEDIUM = 100, LARGE = 1000 };