Binary Integer Literals In C++ 11

Two weeks ago I wrote how happy I was finding out the C++ 14  has gotten around to support binary literals.  However,  If you are stuck with a slightly older compiler (like Visual Studio 2013)   binary literal can also  be easily  expressed in C++ 11!

In his excellent post,  Paul Preney  outlines a tiny framework that will allow writing expressions of the type:

int  can_write_file = 00001_binary;

It is done by user defined literals  processed in by variadic template  functions in a pattern similar to the one outlined in C++ Variadic templates from the ground up.

Roll all the way down to the end of the post for the  complete 50 lines  listing  (including a small demo program)

I Get It Windows, Something Is Locking the File, But What Exactly?

My development environment  consists of several processes running together simulating various server and client applications.  Add a couple of open command prompts to the mix  and  the message:

The process cannot access the file because it is being used by another process.

appears every once in a while.

Windows wouldn’t tell which process is holding your file hostage.  That’s for it to know and you to find out.

In this post I introduce two tools that will help you interrogate the OS for  the  information:

Process Explorer

a free utility from Microsoft.   No installation required,  download it extract it from the zip archive and run.

Click Find  or enter Ctrl-F

image

In the find dialog, you can enter the name of the locked file.  After clicking search,  you can have the name and PID of the offending process.

image

LockHunter

This  freeware windows explorer extension that will  not only find the locking process, it will also let you kill that locking process or force unlocking the file.

You can download the file from lockhunter.com.  Once Installed you can right-click on a file from windows explorer and select What is locking this file? Or What is locking this folder?

image

Conclusion

I like guessing games as much as  the next person,  I just don’t want them in the middle a  busy work day.

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