Uses For The Comma Operator in C++

Arne Olav Hallingstad
11th Match 2011
Home

Introduction

There's not a whole lot of places I'd use the comma operator as it's so easy to miss it's importance if you or someone else is modifying the code down the line, but for extremely short expresesions it does make the code easier to read in my opinion.

The example is taken from a solution to TopCoder.com's SRM 281 DIV 2 250 and shows the usage of the comma operator.

// TopCoder.com SRM 281 DIV 2
// Note that the code below does not work
// for input strings like "50A"
class RunLengthEncoding {
public:
	RunLengthEncoding() {}

	string decode(string text) {
		string decoded;
		for ( int i = 0; i < text.size(); i++ ) {
--->	int count = isdigit( text[ i ] ) ? i++, text[ i - 1 ] - '0' : 1;
			while ( count-- > 0 ) {
				decoded += text[ i ];
				if ( decoded.size() > 50 ) {
					return string( "TOO LONG" );
				}
			}
		}
		return decoded;
	}
};

Versus:

// TopCoder.com SRM 281 DIV 2
// Note that the code below does not work
// for input strings like "50A"
class RunLengthEncoding {
public:
	RunLengthEncoding() {}

	string decode(string text) {
		string decoded;
		for ( int i = 0; i < text.size(); i++ ) {
			int count = 1;
			if ( isdigit( text[ i ] ) ) {
				count = text[ i ] - '0';
				i++;
			}
			while ( count-- > 0 ) {
				decoded += text[ i ];
				if ( decoded.size() > 50 ) {
					return string( "TOO LONG" );
				}
			}
		}
		return decoded;
	}
};

Tweet

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.