20 July, 2009

Useful C++ tricks

from http://prokutfaq.byethost15.com

Odd or even?


bool isOdd(int num){
return num&1?true:false;
}


If the number is odd then it's least significant bit (LSB) is set i.e. it is 1. If it is even then it is 0. When you bitwise and (&) this number with 1, the result would be either 1 if the number is odd or zero if it is even.

Passing 2 dimensional array

Example:
/* This program demonstrates passing a 2 dimensional array of size 4 * 4 */

void myFunction(int(*)[4]);

int main()
{
int a[4][4];
myFunction(a);
return 0;
}

void myFunction(int (*myArray)[4])
{
/* Here you can access the content of the argument passed like any other 2-D array */
/* Example: myArray[2][2]=10; */
}


Passing 3 dimensional array

Example:
/* This program demonstrates passing a 3 dimensional array of size 4 * 4 * 4 */

void myFunction(int(*)[4]);

int main()
{
int a[4][4][4];
myFunction(a);
return 0;
}

void myFunction(int (*myArray)[4][4])
{
/* Here you can access the content of the argument passed like any other 3-D array */
/* Example: myArray[2][2][2]=10; */
}

And an inetresting bit about changing particular bits

No comments: