Is it possible to pass a line of code in a C \ C ++ macro?

For example, I would like to make a debug macro that prints a line of code before trying to execute it. I suppose it should look something like this.

#define TRACE(string) printf("Trying to execute: %s\n",\"string\"); \
                      string

...

void foo() {
  printf("1\n");
}
void bar() {
  printf("2\n");
}

int main() {
  ...
  foo();
  TRACE(bar(););
  ...
}

With expected output

...
1
Trying to execute: bar();
2
...

Well, that’s not how it is done: the compiler complains about illegal syntax. Is there any way to do this at all?

+4
source share
3 answers

You need to use string encoding with #:

#define TRACE(string) printf("Trying to execute: %s\n",#string); \
                      string

Full example:

#include <stdio.h>

#define TRACE(string) printf("Trying to execute: %s\n",#string); \
                          string

void foo() {
  printf("1\n");
}
void bar() {
  printf("2\n");
}

int main() {

  foo();
  TRACE(bar(););
}

output:

1
Trying to execute: bar();
2

+11
source

You must use the "stringification" operator #, which will result in a replacement with "string".

#define TRACE(string) printf("Trying to execute: %s\n", #string); \
                      string
+8
source

do { /* ... */ } while(0), :

#define TRACE(string) do { \
                          printf("Trying to execute: %s\n", #string); \
                          string \
                      } while(0)

, .

if(condition)
    TRACE(foo();)

If you do not wrap it around the construct do { /* ... */ } while(0), it foo()will be called, even if it conditionis false. If you have the following statement else, it will even cause a syntax error.

For more information, see Why use explicitly meaningless do-while and if-else statements in macros? .

+2
source

Source: https://habr.com/ru/post/1599841/


All Articles