Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Call #define multiple times based on a specific value

If you call something like this in C:

#include <stdio.h>

#define REPS ,a
...
int a = 1;

printf("%d" REPS);

It will work, but is it possible to call the REPS macro multiple times based on an unknown value, like for example, that I want to have five inputs in a scanf, yet I want my code to automate it (for example, if #define REPS ,a[i] then: ... ,a[1] ,a[2])?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

It will work, but is it possible to call the REPS multiple times based in an unknown value

No. #define creates a preprocessor macro that you can use in your code, but when the compiler compiles your code, the actual value is substituted for the macro. If you have:

#define FOO 7

for example, then every occurrence of FOO in your code is replaced by 7 before the code is compiled; by the time the compiler sees your code, there's no #define and no FOO, only 7 wherever FOO was. Although there are some other preprocessor commands (e.g. #if) that can control whether a given #define is evaluated at all, there are no other preprocessor control structures (loops etc.).

I want to have five inputs in a scanf, yet I want my code to automate it (for example, if #define REPS ,a[i] then: ... ,a[1] ,a[2])?

You can certainly automate something like that; it's just that the preprocessor isn't the right tool for the job. Consider:

int reps = 5
//...
for (int i = 0; i < reps; i++) {
    scanf(" %d", &a[i]);
}
over 4 years ago · Santiago Trujillo Relatório

0

REPS is evaluated at compile time, so it cannot depend on run-time values in this case a. There are hacks but in general you cannot do compile loops with macros.

I suggest you write a function along these lines instead:

#include <stdio.h>

void print_int_array(size_t n, int a[n]) {
        for(int i = 0; i < n; i++)
                printf("%d%s", a[i], i + 1 < n ? ", " : "\n");
}

int main() {
        print_int_array(0, (int []) {});
        print_int_array(1, (int []) {1});
        print_int_array(2, (int []) {1, 2});
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda