Skip to main content

Come C tricks

Swapping the values of two variables with out using a third!!
x = x ^ y;
y = x ^ y;
x = x ^ y;
All hail the XOR operation
Reference: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html


int c;
c &= (c-1);
check if c == 0

This allows you to check if C is a power of 2 (i.e. 0,1,2,4,8...)



Reading sentences (including spaces) from stdin:

scanf("%s",str); can't read spaces in input string.
To do that, you have to: scanf(" %[^\n]s",str);

Note the space before % within the quotes.

Reference: https://gpraveenkumar.wordpress.com/2009/06/10/how-to-use-scanf-to-read-string-with-space/

Comments