Take care when using comma in C++

A friend had a weird bug while working in C++ last week. As sometimes it’s required he had to convert a string to an integer and instead of writing:

auto result = (SomeEnum) (stoi(s, nullptr, 10));

He wrote this:

auto result = (SomeEnum) (stoi(s, nullptr), 10);

Such a simple case of misplaced parenthesis caused the result to equal 10 instead of whatever s was.
In order to understand what the hell happened here you have to understand how the comma operator works in C++.
In C++ a comma is more than just a separator – it has its own rules and can cause grief if used incorrectly.
For example consider the following code:

auto whoami = ("111", nullptr, SomeFunc(), 42);

Can you tell what would the value be?
Strangely enough (or not) the result will be an integer “42”.
The reason for this strange behavior is that the comma operator works by evaluating each statement from right to left discarding the result other than the last one.
So keep in mind that SomeFunc was executed even if we didn’t get back its return value.
The same goes for the following (simpler) version:

int someInt = (1, 2, 3);

In this case someInt would equal 3.
And you can go complete crazy in a way only suitable for job interviews (from hell):

int someInt = (i = 100, i+= 20, --i);

In conclusion – be careful when using commas because you might not like what you’ll get.

Happy coding…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.