Sunny
Sunny

Reputation: 7604

Array of strings in a Macro

I would like to take an array of strings in a macro. Firstly: is that possible?

IF yes, can I call them one by one based on the index, when I am using them?

Something like this:

#define VAR    "abc", "def", "xyz"

Then when i want to use "def" somewhere,

FUNC(VAR[1]);

Upvotes: 1

Views: 8557

Answers (4)

maverik
maverik

Reputation: 5586

#define VAR(...) const char *FOO[] = { __VA_ARGS__ }
...
VAR("abc", "xyz");
printf("%s\n", FOO[0]);

But note:

  1. Macros are evil.
  2. Declare a variable in macro is the worst idea ever.

Upvotes: 1

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

May be my code helpful to you:

#include<stdio.h>
#include<stdlib.h>
#define STRING_ARRAY  "ONE", "TWO", "THREE", "NULL"

int main(){

    char* STRING[] = {STRING_ARRAY};

    int i=0;
    scanf("%d",&i);
    printf("%s\n",STRING[i]);
    return EXIT_SUCCESS;
}

This also works:

:~$ gcc x.c  -o  x
:~$ ./x
1
TWO
e:~$ ./x
2
THREE  

You have to change in MACRO only in at re-compilation.

Upvotes: 2

Jens Gustedt
Jens Gustedt

Reputation: 78903

Starting with C99 you can use compound literals

#define VAR ((char const*[]){ "abc", "def", "xyz" })

and then use this as VAR[2] or so.

A compound literal is similar to a cast of an initializer, here this is an array of base type char const*. The const is important such that you don't inadvertently try to modify the string literals.

Any modern compiler should be able to fold all different occurrences of that array and of the string literals into one single instance.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

The macro will expand to the text on the right so try to answer your question for yourself.

Here is a way to try to understand macro-s:

FUNC(VAR[1]); <=> FUNC("abc", "def", "xyz"[1]);

Will the one on the right do what you expect? No? So then you can't use it like this. However you can use this for static array initilization and then access the array by index for instance.

EDIT: here is how I propose you to use the MACRO:

char* a[] = {VAR};
FUNC(a[0]);

Upvotes: 0

Related Questions