Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call #define multiple times based on a specific value

new to C language here!

If you can 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 multiple times based in 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])?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading