Has anyone ever had a use for the __COUNTER__ pre-processor macro?

Viewed 51008

The __COUNTER__ symbol is provided by VC++ and GCC, and gives an increasing non-negative integral value each time it is used.

I'm interested to learn whether anyone's ever used it, and whether it's something that would be worth standardising?

19 Answers

I've never used it for anything but a DEBUG macro. It's convenient to be able to say

#define WAYPOINT \
    do { if(dbg) printf("At marker: %d\n", __COUNTER__); } while(0);

It's used in the xCover code coverage library, to mark the lines that execution passes through, to find ones that are not covered.

If I'm understanding the functionality correctly, I wished I had that functionality when I was working in Perl, adding an Event Logging function into an existing GUI. I wanted to ensure that the needed hand testing (sigh) gave us complete coverage, so I logged every test point to a file, and logging a __counter__ value made it easy to see what was missing in the coverage. As it was, I hand coded the equivalent.

Generating Class Type IDs (C++)

I've used __COUNTER__ to automatically generate type IDs for Entities & Colliders in an object-oriented game.

This game uses polymorphism to achieve its functionality. To serialize child objects, I had to figure out a way to store Entity child types & serialize/deserialize them for scene saving & loading. When reading an entity from a save file (deserializing), I needed to know what properties to expect to read; with __COUNTER__, I have a unique and constant ID for each entity class and can load them in as the proper entity type using this ID.

This approach means that to make a new Entity type serializable, all I have to add is typeID = __COUNTER__; within the constructor to overwrite the default ID. In the case of Sprite:

Sprite(/* TODO: Sprite Arguments */) : Entity(/* TODO: Entity Arguments */) {
    typeID = __COUNTER__;
}

... and go on to outline its iostream overloads:

friend std::ostream& operator<<(std::ostream& os, const Sprite& rhs) {
    return os << /* TODO: Outline Output */;
}
friend std::istream& operator>>(std::istream& is, Sprite& rhs) {
    return is >> /* TODO: Outline Input */;
}

It's a very lightweight approach to generating type IDs for your classes, and avoids a bunch of complicated logic. As a preprocessor command it's pretty basic, but it provides a useful tool for some key appliances.

Note: If you want to restart the ID value to 0 when calling the counter, store its value on the generation of your first ID and subtract all subsequent IDs by that value.

Thanks for reading! -YZM

I've used it for a driver shim layer, where I needed to make sure at least one physical driver was enabled.

For example:

#if defined( USE_DRIVER1 )
#include "driver1.h"
int xxx1 = __COUNTER__;
#endif
#if defined( USE_DRIVER2 )
#include "driver2.h"
int xxx2 = __COUNTER__;
#endif
#if __COUNTER__ < 1
#error Must enable at least one driver.
#endif

In our code we forgot to add testcases for some of our products. I implemented now some macros so we can assert at compile time that we have testcases for each product that we are adding or removing.

In this blog post it is used for simulating the defer statement of golang in C++11.

template <typename F>
struct privDefer {
    F f;
    privDefer(F f) : f(f) {}
    ~privDefer() { f(); }
};

template <typename F>
privDefer<F> defer_func(F f) {
    return privDefer<F>(f);
}

#define DEFER_1(x, y) x##y
#define DEFER_2(x, y) DEFER_1(x, y)
#define DEFER_3(x)    DEFER_2(x, __COUNTER__)
#define defer(code)   auto DEFER_3(_defer_) = defer_func([&](){code;})

Then you can do:

int main()
{
    FILE* file = open("file.txt");
    defer(fclose(file));

    // use the file here
    // ....
}

__COUNTER__ is very useful when you are encrypting strings in runtime and you want every string to have a unique key, without storing a counter somewhere for the key of your encryption you can use Counter to be sure that every string has it's own unique key!.

I use it in my XorString 1 header library which decrypts strings in run-time, so if any hackers/crackers try to look at my binary file they won't find the strings there, but when the program runs every string is decrypted and shown as normal.

#pragma once
#include <string>
#include <array>
#include <cstdarg>

#define BEGIN_NAMESPACE( x ) namespace x {
#define END_NAMESPACE }

BEGIN_NAMESPACE(XorCompileTime)

constexpr auto time = __TIME__;
constexpr auto seed = static_cast< int >(time[7]) + static_cast< int >(time[6]) * 10 + static_cast< int >(time[4]) * 60 + static_cast< int >(time[3]) * 600 + static_cast< int >(time[1]) * 3600 + static_cast< int >(time[0]) * 36000;

// 1988, Stephen Park and Keith Miller
// "Random Number Generators: Good Ones Are Hard To Find", considered as "minimal standard"
// Park-Miller 31 bit pseudo-random number generator, implemented with G. Carta's optimisation:
// with 32-bit math and without division

template < int N >
struct RandomGenerator
{
private:
    static constexpr unsigned a = 16807; // 7^5
    static constexpr unsigned m = 2147483647; // 2^31 - 1

    static constexpr unsigned s = RandomGenerator< N - 1 >::value;
    static constexpr unsigned lo = a * (s & 0xFFFF); // Multiply lower 16 bits by 16807
    static constexpr unsigned hi = a * (s >> 16); // Multiply higher 16 bits by 16807
    static constexpr unsigned lo2 = lo + ((hi & 0x7FFF) << 16); // Combine lower 15 bits of hi with lo's upper bits
    static constexpr unsigned hi2 = hi >> 15; // Discard lower 15 bits of hi
    static constexpr unsigned lo3 = lo2 + hi;

public:
    static constexpr unsigned max = m;
    static constexpr unsigned value = lo3 > m ? lo3 - m : lo3;
};

template <>
struct RandomGenerator< 0 >
{
    static constexpr unsigned value = seed;
};

template < int N, int M >
struct RandomInt
{
    static constexpr auto value = RandomGenerator< N + 1 >::value % M;
};

template < int N >
struct RandomChar
{
    static const char value = static_cast< char >(1 + RandomInt< N, 0x7F - 1 >::value);
};

template < size_t N, int K, typename Char >
struct XorString
{
private:
    const char _key;
    std::array< Char, N + 1 > _encrypted;

    constexpr Char enc(Char c) const
    {
        return c ^ _key;
    }

    Char dec(Char c) const
    {
        return c ^ _key;
    }

public:
    template < size_t... Is >
    constexpr __forceinline XorString(const Char* str, std::index_sequence< Is... >) : _key(RandomChar< K >::value), _encrypted{ enc(str[Is])... }
    {
    }

    __forceinline decltype(auto) decrypt(void)
    {
        for (size_t i = 0; i < N; ++i) {
            _encrypted[i] = dec(_encrypted[i]);
        }
        _encrypted[N] = '\0';
        return _encrypted.data();
    }
};

//--------------------------------------------------------------------------------
//-- Note: XorStr will __NOT__ work directly with functions like printf.
//         To work with them you need a wrapper function that takes a const char*
//         as parameter and passes it to printf and alike.
//
//         The Microsoft Compiler/Linker is not working correctly with variadic 
//         templates!
//  
//         Use the functions below or use std::cout (and similar)!
//--------------------------------------------------------------------------------

static auto w_printf = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};

static auto w_printf_s = [](const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vprintf_s(fmt, args);
    va_end(args);
};

static auto w_sprintf = [](char* buf, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf(buf, fmt, args);
    va_end(args);
};

static auto w_sprintf_ret = [](char* buf, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf(buf, fmt, args);
    va_end(args);
    return ret;
};

static auto w_sprintf_s = [](char* buf, size_t buf_size, const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
    vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
};

static auto w_sprintf_s_ret = [](char* buf, size_t buf_size, const char* fmt, ...) {
    int ret;
    va_list args;
    va_start(args, fmt);
    ret = vsprintf_s(buf, buf_size, fmt, args);
    va_end(args);
    return ret;
};

//Old functions before I found out about wrapper functions.
//#define XorStr( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char >( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ).decrypt() )
//#define XorStrW( s ) ( XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t >( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ).decrypt() )

//Wrapper functions to work in all functions below
#define XorStr( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(char) - 1, __COUNTER__, char > expr( s, std::make_index_sequence< sizeof(s)/sizeof(char) - 1>() ); return expr; }().decrypt()
#define XorStrW( s ) []{ constexpr XorCompileTime::XorString< sizeof(s)/sizeof(wchar_t) - 1, __COUNTER__, wchar_t > expr( s, std::make_index_sequence< sizeof(s)/sizeof(wchar_t) - 1>() ); return expr; }().decrypt()

END_NAMESPACE

I have found it useful for displaying steps in a UI. This makes it really easy to add, remove, or reorder steps without worrying about the steps getting mislabeled.

#include <iostream>

#define STR_IMPL(s)  #s
#define STR(s)  STR_IMPL(s)
#define STEP  STR(__COUNTER__) ": "

int main()
{
    std::cout 
        << STEP "foo\n"
        << STEP "bar\n"
        << STEP "qux\n"
        ;
}

Output:

0: foo
1: bar
2: qux

Having it start from 1 instead of 0 is left as an exercise.

__COUNTER__ can be used to establish unique local variables. The problem with __COUNTER__ is that its value is different on each expansion. But what we can do is split our macro into two:

#define MACRO_IMPL(COUNTER, ARG1, ARG2, ..., ARGN)

#define MACRO(ARG1, ARG2, ..., ARGN) MACRO_IMPL(__COUNTER__, ARG1, ARG2, ... ARGN)

So now MACRO_IMPL has a unique counter, via the COUNTER argument value, which it can use to generate local symbols that are defined and referenced multiple times. E.g.

#define CAT(A, B) A ## B
#define XCAT(A, B) CAT(A, B)
#define U(COUNTER) XCAT(__U, COUNTER)

#define REPEAT_IMPL(C, N) for (int U(C) = 0; U(C) < (N); U(C)++)

#define REPEAT(N) REPEAT_IMPL(__COUNTER__, N)

REPEAT (42) { puts("Hey!"); REPEAT (73) { puts("Cool!"); } }

Expansion by gcc -E -:

# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "<stdin>"
# 9 "<stdin>"
    for (int __U0 = 0; __U0 < (42); __U0++) { puts("Hey!"); for (int __U1 = 0; __U1 < (73); __U1++) { puts("Cool!"); } }

I put the loops in one line on purpose; that's a situation where using __LINE__ instead of __COUNTER__ could break.

Related