'how to define a constant array in c/c++?
How to define constant 1 or 2 dimensional array in C/C++? I deal with embedded platform (Xilinx EDK), so the resources are limited.
I'd like to write in third-party header file something like
#define MYCONSTANT 5
but for array. Like
#define MYARRAY(index) { 5, 6, 7, 8 }
What is the most common way to do this?
Solution 1:[1]
In C++ source file
extern "C" const int array[] = { 1, 2, 3 };
In header file to be included in both C and C++ source file
#ifdef __cplusplus
extern "C" {
#endif
extern const int array[];
#ifdef __cplusplus
}
#endif
Solution 2:[2]
In C++, the most common way to define a constant array should certainly be to, erm, define a constant array:
const int my_array[] = {5, 6, 7, 8};
Do you have any reason to assume that there would be some problem on that embedded platform?
Solution 3:[3]
In C++
const int array[] = { 1, 2, 3 };
That was easy enough but maybe I'm not understanding your question correctly. The above will not work in C however, please specify what language you are really interested in. There is no such language as C/C++.
Solution 4:[4]
It's impossible to define array constant using the define directive.
Solution 5:[5]
I have had a similar problem. In my case, I needed an array of constants in order to use as size of other static arrays. When I tried to use the
const int my_const_array[size] = {1, 2, 3, ... };
and then declare:
int my_static_array[my_const_array[0]];
I get an error from my compiler:
array bound is not an integer constant
So, finally I did the following (Maybe there are more elegant ways to do that):
#define element(n,d) ==(n) ? d :
#define my_const_array(i) (i) element(0,1) (i) element(1,2) (i) element(2,5) 0
Solution 6:[6]
#include <string>
#include <iostream>
#define defStrs new string[4] { "str1","str2","str3","str4" }
using namespace std;
...
const string * strs = defStrs;
string ezpzStr = strs[0] + "test" + strs[1];
cout << ezpzStr << endl;
Took me a while to figure this out, but apparently it works like this in C++. Works on my computer anyway.
Solution 7:[7]
Only try to understand what the compiler does. When it finds the HASHTAG , it replaces its content into the place where it's writed. So for example, if u do this:
#define MYARRAY { 5, 6, 7, 8 }
byte list[] = MYARRAY ;
You will get it in the array 'list' . Another way to get the same result is:
#define MYARRAY 5, 6, 7, 8
byte list[] = {MYARRAY} ;
In conclusion, the compliler what does is 'cutting' the hashtag and 'pasting' the content of it. I hope I had solved your doubt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jahhaj |
| Solution 2 | Nicol Bolas |
| Solution 3 | jahhaj |
| Solution 4 | Ethan |
| Solution 5 | Ojos |
| Solution 6 | Silikiln |
| Solution 7 | Jose |
