0

In my C++ code I want to be able to switch between using using arrays and variables, i.e. switch between array[2] and two variables array_0, array_1. However, there are a lot of occurrences of array[2] and I was looking for a way to quick switch between the two. I was trying to use a preprocessor #define statement.

#define array[2] array_0, array_1

int array[2]; //if define is included should become int array_0, array_1; 

However, this gives the following warnings/errors.

line(1): warning: missing whitespace after the macro name
line(2): error: expected unqualified-id before ‘[’ token

From what I've seen, the problem is the square brackets. Is there anyway of making this work and have array[2] replaced with array_0, array_1?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • what do you mean switch between arrays and variables? that makes no sense – DTSCode Jul 14 '14 at 18:19
  • 3
    No. But you can `#define` something that becomes either `array[2]` or `array_0, array_1`. But why would you ever want to do this? – T.C. Jul 14 '14 at 18:20
  • I rather think that even if this worked, it wouldn't do what you wanted it to do – Mooing Duck Jul 14 '14 at 18:24
  • As a quick way to replace, try Shift+Ctrl+H? – Mooing Duck Jul 14 '14 at 18:25
  • What you _can_ do is use some constant like `ARRAY2` and switch between the array and the two vars by writing `#define ARRAY2 array[2]` and `#define ARRAY2 array_0, array_1`, respectively – Mr Lister Jul 14 '14 at 18:30
  • If you really want to switch like that, you will need a lot of defines to make that work, though. I guess you need to translate `array[n]` too? – Mr Lister Jul 14 '14 at 18:33
  • Your macro is evil. If I have the following `array[2] = 5;`, your macro will change it to `array_0, array1 = 5;`, which is ambiguous and will break the code. – Thomas Matthews Jul 14 '14 at 18:51
  • @ThomasMatthews It's not ambiguous. It's just the wrong semantics. – T.C. Jul 14 '14 at 20:00
  • Thanks for the responses. Looks like I'm going to have to do as Mr. Lister and T.C. said and have some constant that will be defined as either an array or a bunch of variables. – RockAwesome Jul 14 '14 at 21:52

1 Answers1

4

This is not possible. What follows #define must be an identifier, and array[2] is not one.

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
  • And as Mr Lister and T.C. said I could define a constant and switch between defining it as an array or a bunch of variables. – RockAwesome Jul 14 '14 at 22:09