Creating Unique Variables with a #define

Feb 3, 2015 at 8:19pm
So I have a friend who is trying to make something in VB, where he has an array of buttons that he gives unique labels to put into an array. He doesn't know beforehand how many he has. He thought that he could use something that he saw in C to do it, but I don't think it can even be done in C. So the question is, is it possible to do something like

1
2
3
4
5
6
7
8
#define button(x) int button(x) = arr[x]

int main()
{
     button(1);
     button(2);
     button(3);
}


So that we get 3 ints button1, button2, and button3?
Feb 3, 2015 at 8:28pm
I don't get it. If you have arr[0], arr[1], and arr[2]... then why do you need button1, button2, button3? Can't you just use arr[0]?

To me, it looks like you're just renaming the variable. Which, if you want to do that... yeah, you could use a #define for that. Almost exactly what you did in your post:

1
2
3
4
5
6
#define button(x) (arr[x])

int main()
{
    button(1) = 5;  // <- same as writing arr[1] = 5;
}


Not that I would do that, but you certainly could. Though I think I must be misunderstanding the question.
Feb 3, 2015 at 9:23pm
Is this what you want?
 
#define button(x) int button##x = arr[x] 
Feb 3, 2015 at 11:07pm
If you want to give labels (aliases) to specific array indices:
1
2
3
int &hello = arr[0];
int &goodbye = arr[1];
std::swap(hello, goodbye); //swaps arr[0] and arr[1] 
Last edited on Feb 3, 2015 at 11:08pm
Feb 3, 2015 at 11:28pm
Well he specifically said C, so I didn't think references were an option.
Feb 3, 2015 at 11:54pm
This is a C++ forum, and when people say C it's usually 50% chance they actually mean C++, despite how dramatically different the languages are.
Feb 20, 2015 at 11:45pm
Yeah, we found out what the problem was. It was a VB issue, so I knew that we wouldn't be able to find the answer here, but he wouldn't believe me. Thanks for the help.
Topic archived. No new replies allowed.