2010-04-26
Yes, it is C. The "const" keyword
The const qualifier can have multiple useful meanings depending on the context.
- In parameter list
size_t strlen(const char *s);
The programmer of strlen() promises you that he/she will not alter the content pointed by s. It is good for you: You do not have to look up the manual for that bit of information. It tells more than you may think for the first time. It is good for the implementor of strlen(). He cannot accidentally write to the area pointed by s.
- Storing partial results as read-only variables.
const double aplusb = a + b; const double amulb = a * b; return 2*amulb/aplusb; // harmonic mean
It helps avoiding accidents and ease interpretation by humans.
- Pointing to literals
const char *appname = "Hello World!";
If you turn on the displaying of warnings in your compiler then you will see that pointing to a literal with non-const pointer is discouraged. It also helps not making bugs.
Kevlin Henney: C++ Stylistics
(Google Talks)
Feel free to watch multiple times.
0
comments
Labels:
coding style,
cpp,
idiom,
Kevlin Henney,
paradigm,
prog,
software design
Exit strategy: Single exit point is less readable
Single exit point produces the pyramid of code syndrome.
bool solve2 ( double a, double b, double c , double& x1, double& x2 ) { bool ret = true; if(a!=0) { double det = b*b - 4*a*c; if(det>=0) { ret = true; det = sqrt(det); double p2a = 1 / (2*a); x1 = (-b - det) * p2a; x2 = (-b + det) * p2a; // The top of the code pyramid } else ret = false; } else ret = false; return ret; }
Using early returns helps keeping the error handing and productive code apart.
bool solve2 ( double a, double b, double c , double& x1, double& x2 ) { // Checking for trivial errors and trivial solutions if(a==0) return false; double det = b*b - 4*a*c; if(det<0) return false; // Main part without pyramid det = sqrt(det); double p2a = 1 / (2*a); x1 = (-b - det) * p2a; x2 = (-b + det) * p2a; return true; }
Note: This function solves the quadratic equation (a * x^2 + b * x + c = 0).
Note: You have to be careful with the multiple exit point style if you are acquiring resources (opening files, allocating memory, ...), because it can lead to leaks. Avoiding these kind of leaks is simpler in C++ than in most languages, because the lifetime of acquisitions can be bound to scope.
0
comments
Labels:
c,
coding style,
cpp,
prog,
RAII,
return,
single exit
Yes, it is C. Smaller scope better scope
Once upon a time there lived a paradigm (sorry, that is an ugly word, but I don't know better) which told the programmer to declare all the variables at the beginning of the function. This paradigm was enforced by the compiler in Pascal, C and many other languages. You can guess. It was easier to write compilers that way. Then came the new winds with C++ (maybe it wasn't the first) which introduced RAII (Resource acquisition is initialization) which gave us three brand new concepts at once.
Next: Exit strategy: Single exit point can be easily bad.
- Variable scoping
- Lifecycle management by scope (calling destructor when execution reaches the end of it's scope)
- Bounding lifecycle of a variable to an object
for(int i=0; i<10; ++i){ printf("%d^2 = %d\n",i,i*i); }The new paradigm (woof) is that a variable should have the smallest scope possible to ease reading and interpretation of code (by humans).
Next: Exit strategy: Single exit point can be easily bad.
0
comments
Labels:
c,
coding style,
cpp,
lifecycle,
paradigm,
prog,
RAII,
scope
2010-04-20
How to create a fast thread-safe singleton initialization in C++
1st: We need a lock. On windows it can use critical sections. Keywords: critical section, lock
singleton.h:
Feel free to search the web for the keywords, or any word you read here.
class Lock { CRITICAL_SECTION mSection; public: Lock(){ InitializeCriticalSection(&mSection); } ~Lock(){ DeleteCriticalSection(&mSection); } void Acquire(){ EnterCriticalSection(&mSection); } void Release(){ LeaveCriticalSection(&mSection); } };2nd: We need a guard for the lock. Just for convenience and to be foolproof. Keyword: RAII, guard. See also: auto_ptr.
class Guard { Lock *pLock; public: Guard(Lock &lock) : pLock(&lock) { pLock->Acquire(); } ~Guard(){ pLock->Release(); } };3rd: We can get down to business with our singleton. Do not forget to hide the default constructors and the '=' operator. Keywords: singleton, multi-thread, thread-safe, storage, operator overloading.
singleton.h:
class Singleton { public: static Singleton *GetInstance(); // other public members private: Singleton(); ~Singleton(); Singleton(const Singleton&); const Singleton& operator=(const Singleton&); static Singleton* pInstance; static Lock instanceLock; // other private members };singleton.cpp:
#include "singleton.h" // Storage place for static members: Singleton* Singleton::pInstance = 0; Lock Singleton::instanceLock; Singleton::Singleton(){ /* as you wish */ } Singleton::~Singleton(){ /* as you wish */ } Singleton* Singleton::GetInstance() { if(pInstance) return pInstane; Guard g(instanceLock); if(!pInstance) pInstance = new Singleton(); return pInstance; }
Feel free to search the web for the keywords, or any word you read here.
0
comments
Labels:
best practice,
cpp,
guard,
lock,
multi-thread,
prog,
RAII,
singleton
2010-04-16
Shut up wonan get on my horse!
Look at my horse; my horse is amazing.
Give it a lick. “MMMmm! It tastes just like raisins!”
Have a stroke of it’s mane, it turns into a plane,
and then it turns back again when you tug on it’s winky.
“Oooo that’s dirty!” Do you think so?
Well I better not show you where the lemonade is made -
Sweet lemonade, mmmm sweet lemonade.
Sweet lemonade, yeah sweet lemonade.
Get on my horse I’ll take you ’round the universe -
and all the other places, too.
“I think you’ll find that the universe pretty much covers everything.”
Shut up woman, get on my horse.
http://www.shutupwomangetonmyhorse.com/
Give it a lick. “MMMmm! It tastes just like raisins!”
Have a stroke of it’s mane, it turns into a plane,
and then it turns back again when you tug on it’s winky.
“Oooo that’s dirty!” Do you think so?
Well I better not show you where the lemonade is made -
Sweet lemonade, mmmm sweet lemonade.
Sweet lemonade, yeah sweet lemonade.
Get on my horse I’ll take you ’round the universe -
and all the other places, too.
“I think you’ll find that the universe pretty much covers everything.”
Shut up woman, get on my horse.
http://www.shutupwomangetonmyhorse.com/
2010-04-15
Dogs and polar bears
A kutyák és a jegesmedvék barátok
http://bazzinga.com/cute-animals/2010/02/26/dogs-and-polar-bears-are-friends.html
http://bazzinga.com/cute-animals/2010/02/26/dogs-and-polar-bears-are-friends.html
2010-04-13
Etióp szorzás / Ethiopian Multiplication
@ Rosetta code
http://rosettacode.org/wiki/Ethiopian_Multiplication
Különösen finom / Extraordinarily tasty:
C++ template implementation
http://rosettacode.org/wiki/Ethiopian_Multiplication#C.2B.2B
http://rosettacode.org/wiki/Ethiopian_Multiplication
Különösen finom / Extraordinarily tasty:
C++ template implementation
http://rosettacode.org/wiki/Ethiopian_Multiplication#C.2B.2B
2010-04-08
2010-04-07
Codepad
~ is an online compiler/interpreter, and a simple collaboration tool. Paste your code below, and codepad will run it and give you a short URL you can use to share it in chat or email.
http://www.codepad.org/
2010-04-02
Színesfém / Ferrous
English version follows...
http://bombahir.hu/belfoeld/hirek/1803-kabellopas-a-gripen-bazison
http://bombahir.hu/publicisztika/bombagyar/1804-dikma-szinesfim
Köszönet Csepinek
English version
Long story short: A piece of power wire was stolen from a Hungarian military airport by some poor people. The airport became disabled.
Thanks to Csepi
Repülőtér: 500 milliárd forint. Drótvágó 500 forint. Két vágással megbénítani egy repülőteret: priceless.
http://bombahir.hu/belfoeld/hirek/1803-kabellopas-a-gripen-bazison
http://bombahir.hu/publicisztika/bombagyar/1804-dikma-szinesfim
Köszönet Csepinek
English version
Airport: 500 billion HUF. Wire cutter: 500 HUF. Disabling an airport with one cut: priceless.
Long story short: A piece of power wire was stolen from a Hungarian military airport by some poor people. The airport became disabled.
Thanks to Csepi
Subscribe to:
Posts (Atom)