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

237
Views
Cómo acceder a una macro desde una cadena que contiene su nombre

En C, si tengo

 #define NUMBER_TWO 2 char* string = "NUMBER_TWO";

¿Cómo puedo pasar de una string al valor 2?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

#define NUMBER_TWO 2 ni siquiera existe en tiempo de ejecución.

En teoría, es incluso desconocido para el compilador propiamente dicho, ya que ha sido manejado por el tokenizador.

Lo que esto significa es que necesitará crear algún tipo de búsqueda usted mismo.

 if ( strcmp( string, "NUMBER_TWO" ) == 0 ) { ... NUMBER_TWO ... } else { ... ??? ... }

Por supuesto, si tuviera que buscar muchos, se debería usar un mejor enfoque que una serie de llamadas strcmp .

over 4 years ago · Santiago Trujillo Report

0

¿Quizás OP es interesante es un abuso de código de macro?

Use #macro_parameter para formar la cadena "macro_argument" .

 #include <stdio.h> #define NUMBER_TWO 2 #define NUMBER_THREE 3 #define NUMBER_FOUR 4 #define TEST_AND_RETURN(s, m) \ do { if (strcmp((s), #m) == 0) return (m); } while (0) int string_to_value(const char *s) { TEST_AND_RETURN(s, NUMBER_TWO); // Only 1 coding of NUMBER_TWO TEST_AND_RETURN(s, NUMBER_THREE); // Maybe the clear way instead, or are 2 NUMBER_FOUR a concern? if (strcmp(s, "NUMBER_FOUR") == 0) return NUMBER_FOUR; return -1; } int main() { char* string = "NUMBER_TWO"; printf("%d\n", string_to_value(string)); printf("%d\n", string_to_value("NUMBER_THREE")); printf("%d\n", string_to_value("NUMBER_FOUR")); }

Producción

 2 3 4
over 4 years ago · Santiago Trujillo Report

0

#define NUMBER_TWO 2 es parte del preprocesador. NUMBER_TWO se reemplaza con 2 en el código fuente y luego se compila. No existe ningún rastro de NUMBER_TWO en tiempo de ejecución.

Tienes que escribir algo que tome una cadena y devuelva macros específicas. La mejor manera de resolver esto depende de lo que esté haciendo con el valor. Si tiene muchas macros a las que desea acceder a través de una cadena, una forma simple sería ponerlas en un hash.

 #define NUMBER_TWO 2 char* string = "NUMBER_TWO"; // This is just an example. You'll have to write a hash, // or better use a library such as GLib. IntHash *stuff = int_hash_new(); int_hash_insert(stuff, "NUMBER_TWO", NUMBER_TWO); int num = int_hash_fetch(stuff, string);

Pero en este punto, puede omitir la macro e inicializar el hash directamente.

 char* string = "NUMBER_TWO"; IntHash *stuff = hash_new(); int_hash_insert(stuff, "NUMBER_TWO", 2); int_hash_insert(stuff, "NUMBER_THREE", 3); int_hash_insert(stuff, "NUMBER_FOUR", 4); int num = int_hash_fetch(stuff, string);
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!