My Notes about C++
Funny tricks
#define foo(...) printf(__VA_ARGS__);
Unused
The following snippet can be used to suppress the warning: unused-result.
template<typename T>
void inline UNUSED(const T&){}
It works well and do NOT affect any efficency in c++.
Float trap
Guess what’s the output of the following program?
int i=0;
for(double x=0;x<10;x+=0.1){
i++;//we means to run i++ 100 times.
}
//here, we thought i=100.
cout<<i<<endl;
I run it in my linux computer, and it outputs 101
, incredibly right?
The secret is, when adding 0.1 to a double variable x
100 times, it could be x may not equal to 10 exactly.
Run the following code to investiage what happens meanwhile?
int i=0;
for(double x=0;x<10;x+=0.1){
i++;
cout<<i<<setprecision(20)<<x<<endl;
}
cout<<i<<endl;
In a nutshell, this is caused by accumulated float error.
Sort trap
To use function sort
in
- irreflexive: For all a, comp(a,a)==false
- antisymmetric: if comp(a,b)==true, then comp(b,a)==false
- transitive: if comp(a,b)==true and comp(b,c)==true then comp(a,c)==true.
There is a error case, extracted from a project. This program will crash. If you’re interested, try to find out why!
Leave a Comment
Your email address will not be published. Required fields are marked *