Binary Integer Literals In C++ 14

With C++  close relationship  with the hardware.  I was always mystified by the lack of  support for base 2  literals.   It’s  common to see header files such as :


const unsigned int can_read_files   = 1; // 00000001
const unsigned int can_write_files  = 2; // 00000010
.
const unsigned int can_delete_files = 32; //00100000

It works but I find this  less readable than it could be.  a typo is no readily obvious and can trigger strange behavior .

That is way I was pleased to find out that with C++ 14  you can now enter binary literal directly by  prefixing it with either 0b  or 0B :

const unsigned int  can_delete_files = 0b00000001;
const unsigned int  can_write_files  = 0b00000010;
const unsigned int  can_move_files   = 0b00000100;

Which  I find more to the point.

Conclusion

Whenever possible it’s  better to leave the boring repetitive  computation stuff  to the compiler it’s much better at this than us.

Save Visual Studio’s Configuration for a Rainy Day

Visual Studio is one of the best IDEs for C++ development. It has a good mix of  powerful tools  and ease of use.

One downside of VS is how easy it is to mess up the windows layout, and other environment settings.   Another downside is that it tends to happen  at the most inconvenient  times.

Saving the IDE layout when everything is  looking and working the way I like. Lets me do a quick reset to my preferred setup without having to google around for ways to restore a  MIA tab.

The procedure is easy and works the same for recent VS versions:

Select Tools –> Import And Export Settings

image

Select the Export radio button:

image

In the next window,  you can select which settings you want to export. I usually export the general settings only, but  shop around and see if  there is anything else you’d want to save.

image

(You can expand the General Settings to subcategories.  I found its easier  to save the whole tree, but you can  fine tune your  selection if it suits you)

The next windows ask you for a save location and file name. I suggest you select a location  that will survive a hard disk disaster, for example, a backed up network directory.  You can also  check the file into a source control repository as it is a plain  XML  file.

image

That’s it!   the next time Visual Studio change things under your feet  you can show it who’s the boss by importing the file  you just saved:

Select Tools –> Import Export Settings:

image

The next windows let you save your current (possibly messed up)  settings  before you override them.  Take the opportunity to do so.  it will take less than a second to delete this file if everything goes well.

image

In the next window browse for your file (or select it from the Recent Files list if its there )

image

The next screen asks you to confirm the import,  the list should contain  the settings you exported earlier :

image

Once the import is done,  your IDE should return to its old self.

Conclusion

It’s not  rocket science  but it does save time. Like anyone who used source control for any length of time know,  sometimes it’s much easier to revert to an older version  than trying to clean up a mess one menu option at a time.

How Developers Are Like Pigeons

In one of his most well know experiments,  B. F. Skinner – the  founder of branch of psychology  known as Radical Behaviorism,   set an automated mechanism  to  give pigeons food  pellets on every predefined constant interval.   Nothing the pigeons  did had anything to do with whether or not they will get the food.  Yet the pigeons appeared to associate getting it with  whatever they were doing at the time.   One of the birds walked in circles  around the cage,  others repeatedly moved their body in a particular way  and some birds did nothing.

No matter what a pigeon did, at the end (of the time interval) it was rewarded with a delicious pellet of food.  Providing further proof that whatever it was doing worked yet again which lead in turn, to a repetition of  the action during the next waiting period.

This simple experiment tried to explain how people come to associate events in their life to  unrelated behaviors and believes also known as superstitions.

While we  developers do not work for food pellets (unless you consider pizza)  we are known to be sensitive to our software not working as expected.  Misbehaving software leads to all kinds of unpleasantness ranging  from uncomfortable embarrassment,  through a never ending all-nighters and all the way to  billions of dollars in  losses.   In an attempt to avoid these uncomfortable situations, and similar to Skinner’s pigeons,  many of us developed a few rituals in our code serving no real purpose other than  warding off imaginary code failures.

here are a few examples I run into :

1. Checking for  a null when calling a new operator  I am sure everyone has seen something similar to this code snip:

  	myClass* mc = new myClass();
  	if (mc == NULL)
  	{
	  Log("Could not allocated memory for  myClase");
  	}

With any modern C++  compiler, the if statement will  never get executed.  The  new operator’s  default behavior is throwing an exception when failing to create the object.    Years ago this kind of code made sense in C code when  as C dynamic allocation function  malloc  returned  a 0 (NULL) on failure. Later in 1998 ,  due to one of many  noncompliances with the standard ,  Microsoft’s Visual Studio 6  C++  compiler, generated code which returned a null by default instead of throwing and exception.  It was fixed in the next version of VS –  15 years ago!  My best guess is that new developer notices this pattern in old code and end up copying it to their own new code “just to be on the safe side” copying it to their own new code and unwittingly continuing the chain.
It is, in fact, possible to have the new operator return a null by calling

myClass* pMc = new(std::nothrow) myClass();

or, by overloading the new operator,  but usually this is not the case.

2. Using NULL or even worse – 0  instead of nullptr:   the nullptr keyword was introduced in C++11 , ending years of having to define  the line:

#define NULL 0

In a header file visible to all  source files.  Yet, more than 5 years later people  keep using a syntax similar to the if  statement in  the previous example. Just in case the compiler didn’t get the memo   that nullptr is an invalid pointer evaluating to  0.

3. Inilizieing an std:string to an empty string:

std::string myString = “”

The of std::string’s  default constructor,  guarantees  the newly created string is empty. Assigning it an empty string literal has no practical value.

3.  having an else clause after a throw

if (myString.empty())
{
	throw myException("Fatal : Empty string")
}
else
{
	myString = myString
}

If the string is indeed null  triggering  the throw statement,  program execution path will be redirected to the closes suitable catch clause skipping the code following the if . The only way the else code will ever get executed is if somehow the throw keyword  is ignored by the compiler, but then  with the compiler producing unpredictable code wouldn’t an empty string be least of our worries ?

Conclusion

Superstitions code may seem harmless at first glance,  but it has a hidden price in code readability and possibly in performance. This kind of code is often difficult to root out as over time we no longer question its validity. Doing  code review and/or paying close attention to the compiler or static analyzer’s  warning  is the best way to clean up these parasitic code segments.

Leave a comment with other examples of superstitions code

Auto Escaping C++ Strings

Just a few weeks after celebrating C++’s  raw strings.  I found myself writing  regular expressions  in Visual Studio 2012. I was disappointed to find out VS 2012  it did not support raw strings.     It’s streaking just how half-baked VS 2012  is.  I think it safe the assume Microsoft Visual Studio’s marking team insisted  on sticking to a 2-year product release cycle while the technical team protested they need more time to implement the then new C++ 11 standard.  The compromise  was a product with only some of the exciting  new  C++  features in place.  The rest had to wait for VS 2013/2015.   As it turned out one of the casualties were raw strings.

Regex are difficult to read on their on,  writing and reading long escaped regex is a form of torture.   Fortunately the escaping and unescaping  parts follow  simple rules can be done automatically.

tomeko.net  provides tools to escape and unescape a C++ string:

image

The example above escapes a regex matching a positive float enclosed by double quotes:

“\d*\.?\d+”  ->   “\\\d*\\.?\\d+\”

Conclusion

When forced to escape C++ string manually, it’s best to leave this daunting task to a computer  program which will do a faster, better job with less mistake.

Or, be more vocal about upgrading to a newer compiler.

Using User Defined Types With STL Associative Containers

Consider the struct:

struct ProductKey
{
	std::string brand;
	std::string model;
	int type;
	int version;
};

Using  it in a  std::set will generate a compile time error.

#include  <set>

int main()
{
	std::set<ProductKey> productSet{
		{ "Best Prod", "M1" , 1, 3 },
		{ "Best Prod", "M2" , 32, 3 },
		{ "Value Prod", "P2" , 32, 3 }
	};
}

binary ‘<‘: no operator found which takes a left-hand operand of type ‘const ProductKey’

std::set internal structure calls for a less functor that given, two ProductKey objects, will determine which should be placed in front of the other in an ordered list.

by default std::set  uses std::less,  as we can see from std::set full declaration (line 4):

   		template<

  		class Key,
  		class Compare = std::less<Key>,
  		class Allocator = std::allocator<Key>

  		> class set;

The default less operator employs the ‘<’ operator to compare the  two keys:

template <class T> struct less {
  bool operator() (const T& x, const T& y) const {return x<y;}
  };

As our ProductKey  do not have  a  ‘<’  operator   defined for it, compilation fails.

One possible solution is  to overload the ‘< ‘  operator for the ProductKey   user type. Once it is defined, the default  std::less implementation  can  use this operator  during compilation.  However,  this will actually be a case of doing  too much.   The only consumer of this new ‘<’  operator will be the associative container. There is no need to expose the new operator to any other component which includes  ProductKey   (if nobody needs it don’t implement it!).  It will be more prudent to do the  minimum needed and simply overload the less functor instead.

defining it in the std namespace will enable us to plug our new less functor into the default std::set declaration:

template<> struct std::less<ProductKey>
	{
		bool operator() (const ProductKey& prod1, const ProductKey& prod2) const
		{
			if (prod1.brand != prod2.brand)
			{
				return prod1.brand < prod2.brand;
			}

			if (prod1.model != prod2.model)
			{
				return prod1.model < prod2.model;
			}

			if (prod1.type != prod2.type)
			{
				return prod1.type < prod2.type;
			}

			return prod1.version < prod2.version;
		}
	};

the empty <>  after the template keyword  in line 1 indicate that this is a specialized template.  That is , when the compiler tries to instantiate the less<T> functor  where T is  ProductKey  it will consider our template definition instead of the more  general  std::less functor defined in the standard library.

We can improve the less  functor’s implementation  by  using  std::tie. This function, included in <tuple>,   creates a tuple out  of  the values supplied to it ,  Since ‘< ‘  is defined for the tuple type  by the standard library ,  our std::less functor can be rewritten as

template<> struct std::less<ProductKey>
{
	bool operator() (const ProductKey& prod1, const ProductKey& prod2) const
	{
		return (std::tie(prod1.brand, prod1.model, prod1.type, prod1.version) <
		std::tie(prod2.brand, prod2.model, prod2.type, prod2.version));
	}
};

which is no only more readable,  It’s  also less error prone and not as boring to write!

So the complete example is:


#include <string>
#include <set>
#include <tuple>


struct ProductKey
{
	std::string brand;
	std::string model;
	int type;
	int version;
};

template<> struct std::less<ProductKey>
{
	bool operator() (const ProductKey& prod1, const ProductKey& prod2) const
	{
		return (std::tie(prod1.brand, prod1.model, prod1.type, prod1.version) < 
			std::tie(prod2.brand, prod2.model, prod2.type, prod2.version));
	}
};

int main()
{
	std::set<ProductKey> productSet{
		{ "Best Prod", "M1" , 1, 3 },
		{ "Best Prod", "M2" , 32, 3 },
		{ "Value Prod", "P2" , 32, 3 }
	};
}
Conclusion

Plugging your code into STL’s containers and algorithms,  Enables  you to  make  your code more robust and maintainable with less effort.  Most important it can make it more fun to write.