woryzower
woryzower

Reputation: 976

Using c macro for variables

I want to access several variables of the form:

int arr1=1;
int arr2=1;
int arr3=1;

So I wrote

#define arr(i) arr##i

but following code piece doesnt work as i expect

#include <stdio.h>

int main(){
int arr1=1;
int arr2=1;
int arr3=1;
int j;
    for(j=1; j<3; j++)
        printf("%d",arr(j));

return 0;
}

Upvotes: 0

Views: 290

Answers (3)

MOHAMED
MOHAMED

Reputation: 43518

The macro code is used for pre-processor phase and not for the runtime phase

if you generate your preprocessor code with gcc -E. You will see that your code is equivalent to:

int main(){
int arr1=1;
int arr2=1;
int arr3=1;
int j;
    for(j=1; j<3; j++)
        printf("%d",arrj);

return 0;
}

When you build your program, the gcc generate anoter c code from your c code and in which it replace all macros in your code by the macro contents( This phase is called preprocesser phase). and then generate asm code and then generate the binary file.

You can see the generated c code (from your code) by the gcc -E: code of preprocessor phase

Upvotes: 3

DigitalRoss
DigitalRoss

Reputation: 146053

So that's going to produce arrj as a result.

The macro phase of C is something that happens before the program is run, even before it is parsed as actual C.

Long ago, the preprocessor was a totally separate program that knew very little about the C language.

Like most compilers today, cc back then just ran the different phases. Before it ran the compiler, assembler, and linker, it ran cpp, the C preprocessor.

And cpp just parsed the definitions, then it expanded the macros, and then it quit. Then cc would run the compiler. These days, the macro expansion is built in to the compiler proper but it processes the textual input of the program according to the original design.

There is still a /usr/bin/cpp on some systems today, but it's usually just a shell script that runs the compiler image with options that say don't compile.

Upvotes: 0

unwind
unwind

Reputation: 399713

You cannot do this. Variable names don't exist at runtime in C.

Your macro will expand to arrj, which is an undefined variable name. Use a proper array:

int arr[] = { 1, 1, 1 };

then print arr[j], but loop like this:

for(j = 0; j < sizeof arr / sizeof *arr; ++j)
  printf("%d\n, arr[j]);

Upvotes: 6

Related Questions