Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
Can one pass a code string into a C\C++-macro?

For example I'd like to make a debug macro which prints a code string before attempting to execute it. I suppose it should look something like that

#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, THIS is not how one does it: compiler complains about illegal syntax. Is there a way to do it at all?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You need to use stringification using #:

#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

live example on ideone

over 4 years ago · Santiago Trujillo Report

0

You must use the "stringification" operator, #, which will cause substitution with "string".

#define TRACE(string) printf("Trying to execute: %s\n", #string); \
                      string
over 4 years ago · Santiago Trujillo Report

0

In addition to the previous answers, wrap your macro around a do { /* ... */ } while(0) construct, as in:

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

Otherwise, it may cause errors, e.g.

if(condition)
    TRACE(foo();)

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

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!