13,770,697 members
Technical Blog
alternative version

#### Stats

7.6K views
3 bookmarked
Posted 11 Feb 2013
Licenced CPOL

# Digit Separators in C++

, 11 Feb 2013
Lawrence Crowl's paper describes a proposal the C++ standard to add digit separators to C++. In this blog post, we will look at what we can do for this problem in C++ as it currently is.

## Problem

Here is the statement of the problem as described by Lawrence Crowl:

• Pronounce `7237498123`
• Compare `237498123` with `237499123` for equality
• Decide whether `237499123` or `20249472` is larger

The paper then goes on to describe a proposal the C++ standard to add digit separators to C++. In this blog post, we will look at what we can do for this problem in C++ as it currently is.

Doing this involves (ab)using the preprocessor `##` operator which concatenates 2 tokens. Using this yields two different options. We will use the number `1234567` as an example for these 2 options.

## Option 1 – Self-contained But Not Terse

```1: #define n 1 ## 234 ## 567
2:
3: int j = n;
4:
5: #undef n
```

This option has the advantage that anyone that knows C would be able to figure out what is going on without looking at any other code. The disadvantage is that this is definitely not terse.

## Option 2 – Terse But Requires Macro

Given the macro below:

```1: #define NUM_HELPER(a,b,c,d,e,f,g,...) a##b##c##d##e##f##g
2:
3: #define NUM(...) NUM_HELPER(__VA_ARGS__,,,,,,,,,)
```

we can write the example number `1234567` as below:

```1: int j = NUM( 1,234,567 );
```

The advantage is that this option is terse. It also has the same format that is commonly used outside of programming. The disadvantage is that the code looks pretty confusing unless you know what NUM does. The other disadvantage is that the macro also pollutes the namespace.

While both of these approaches are inferior to C++ native support for digit separators, the two options described above work with C++ now.

Please let me know what you think and which option you like better.

- John Bandela

## About the Author

 Software Developer self employed United States
I started programming in Basic in the 4th grade. In 8th grade, I convinced my parents to buy me Visual C++ 1.0. I discovered I really enjoyed C++, and have been programming in it since. I attended the University of Florida and majored in Computer Science graduating with honors with a 4.0 GPA. I then attending Medical School and obtained my Doctor of Medicine degree.

I have used my computer skills to help me in my medical practice. I also enjoy programming in C++ just for fun, trying to discover new ways of solving problems or applying C++ to new areas. My latest interest has been in creating a component system for C++ allowing components created with 1 compiler to be easily used by another compiler.

## Comments and Discussions

 -- There are no messages in this forum --