-5

While reading this code in .h file about tlm,something that confuses me comes up:

//
// Generators for Setters and Getters.
//
#define CHIATTR_PROP_GETSET_GEN(name, type)         \
    type Get ## name (void) const { return name ; } \
    void Set ## name (type new_v) { name = new_v; }

#define CHIATTR_PROP_GETSET_GEN_FUNC_NAME(func_name, prop_name, type)   \
    type Get ## func_name (void) const { return prop_name ; }   \
    void Set ## func_name (type new_v) { prop_name = new_v; }

and it is used like this:

CHIATTR_PROP_GETSET_GEN(ReturnNID_StashNID, uint16_t)
CHIATTR_PROP_GETSET_GEN_FUNC_NAME(ReturnNID,
                          ReturnNID_StashNID,
                          uint16_t)

what happens in this sentence?

type Get ## name (void) const { return name ; } \

Eagerly awaiting the answer!

Lundin
  • 195,001
  • 40
  • 254
  • 396
celia
  • 25
  • 5
  • I'd say that this is perhaps a clear indication that the code was written by a C programmer who has not yet grasped function overloading and templates? :) Anyway, creating functions with macros would be bad practice in C as well. – Lundin Jan 10 '23 at 10:56
  • @Lundin Or rather the code was written by a C programmer as a part of a C library for use in C programs, and the C++ tag is a usual misattribution. – n. m. could be an AI Jan 10 '23 at 11:02
  • @n.m. `func_name (void) const` <-- or not. C does not have member functions. Why I just deleted the C tag. – Lundin Jan 10 '23 at 11:04
  • @Lundin hmm you are right this is actually from a C++ library. – n. m. could be an AI Jan 10 '23 at 11:13
  • @n.m. In which case there are many ways that this code should have been written instead. Inheritance, function overloading, templates... I would call out major code smell if I'd see someone mucking around with ## for such purposes. This would never have passed code review either. – Lundin Jan 10 '23 at 11:18
  • @Lundin given that the code is © 2019 Xilinx Inc. it probably did pass some kind of review somehow. – n. m. could be an AI Jan 10 '23 at 11:20
  • 1
    @n.m. It's from a silicon vendor? Say no more. Then it makes perfect sense, the silicon vendors of the world are known for their never-ending competition over who can produce the most horrible software. It compiles - ship it. – Lundin Jan 10 '23 at 11:25

1 Answers1

2

The ## operator takes two separate tokens and pastes them together to form a single token.

From your examples :

CHIATTR_PROP_GETSET_GEN(ReturnNID_StashNID, uint16_t)

Would be replaced at the preprocessor step by the following code :

uint16_t GetReturnNID_StashNID (void) const { return ReturnNID_StashNID; }
void SetReturnNID_StashNID (uint16_t new_v) { ReturnNID_StashNID = new_v; }
Issylin
  • 353
  • 2
  • 3
  • 11