Category

Showing posts with label Syntax. Show all posts
Showing posts with label Syntax. Show all posts

Friday, January 6, 2012

Order of bitwise operation and ==

The following code was supposed to give the i-th bit of a 16bit integer:
However, get_ith(6, 0) gives us 1 instead of 0. Why?

It turns out that x&y==0 is interpreted as x & (y==0), which is 0 (false), thus 1 is returned instead. To fix the code, we should enclose x&y using parenthesis: if((x&y)==0). The correct code is the following:

Friday, September 9, 2011

C++ namespace: global variables

Suppose you have a "mynamespace.h", which defines your own namespace called "mynamespace", and you have a "mynamespace.cpp", which includes the implementation. Then you include "mynamespace.h" in your main.cpp. You should avoid defining global variables in "mynamespace.h", such as

namespace mynamespace {
double length;
}

otherwise you will get errors like "multiple definition of ***" during the linking stage. What you should do, is to declare the global variables, for example

namespace mynamespace {
extern double length;
}

And then you define the global variables in "mynamespace.cpp".

Visitors