Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda