Re: I learned a new macro today __COUNTER__

Somehow I needed three macros to create variable names:

#define VAR_1(a,b) a##b
#define VAR_2(a,b) VAR_1(a,b)
#define VAR(a) VAR_2(a,__COUNTER__)

int VAR(x) = 100;
int VAR(x) = 101;
int VAR(x) = 102;
int VAR(x) = 103;

void setup() 
{
  Serial.begin(115200);
  Serial.println(x0);
  Serial.println(x1);
  Serial.println(x2);
  Serial.println(x3);
}

void loop() 
{
  delay(10);
}

Tested in Wokwi simulation: A test with __COUNTER__ - Wokwi ESP32, STM32, Arduino Simulator

In Wokwi, it works with: Uno, Mega, Nano, Raspberry Pi Pico, STM32.
It does not work with: ESP32 or any of its newer variants, such as ESP32-C3, ESP32-S2.

1 Like

Just adding information:

Macro listing:

" https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html

" Standard Predefined Macros (The C Preprocessor)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.