5

Hi This is legal code for the compiler I use:

#use delay(clock=4M)

now I need to substitute the inside brackets text clock=4M with a macro. The digit 4 might be any digit, it should be modifiable. I tried with this

#define CLOCK_SPEED(x)        clock=xM

but didnt work.

Radoslaw Krasimirow
  • 1,833
  • 2
  • 18
  • 28
  • 1
    Define "didn't work". What did you *expect* and what did you *get*? Having said that, you need a second macro in the chain that expands `x` before expanding `clock=xM`. – John Bode Aug 24 '15 at 18:59
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. – too honest for this site Aug 24 '15 at 19:00
  • 1
    The OP's intent is quite clear to me, as is his actual problem and the way to fix it. – Sébastien Dawans Aug 24 '15 at 19:10

1 Answers1

13

What you want is the preprocessor concatenation operator, ##.

#define CLOCK(x) clock=x##M

void some_function() {
        CLOCK(4);
}

The outcome:

tmp$ cpp -P test.c 
void some_function() {
 clock=4M;
}

On a side note, macros like these are often the cause of hard-to-find bugs. It is usually recommended to write them like this:

#define CLOCK(x) do { clock=x##M; } while(0)
Community
  • 1
  • 1
Snild Dolkow
  • 6,669
  • 3
  • 20
  • 32
  • Yes it works I will click to accept the answer as soon as I am allowed to. – Radoslaw Krasimirow Aug 24 '15 at 19:06
  • How does your recommendation make bugs easier to find? – Fiddling Bits Aug 24 '15 at 19:43
  • 1
    It doesn't -- it reduces the risk of introducing them. Imagine a macro like `#define STUFF(x) a=x; b=x`. Used plainly, it's okay: `STUFF(x);` will be just fine. However, here's a worse scenario: `if (x > 3) STUFF(x);`. This compiles, but it preprocesses into `if (x > 3) a=x; b=x` -- so `b` will *always* be set! This problem is not at all obvious when reading the source code, so tracking this problem down may be difficult. This kind of problem is most likely to occur when someone changes a one-statement macro into a multiple-statement macro. And that's why using do-while-0 is a good habit. – Snild Dolkow Aug 24 '15 at 20:03