You are not logged in.
Pages: 1
I'd like to define an array in my C programme above the main function and then call it like this...
#define x {4, 4.6, 5, 2.3}
int main() {
double y;
y = x[2];
return 0;
}
But when I try to compile this, I get the error "error: expected expression befor '{' token." I don't even have a '{' token in the code. Can anyone help me? Thanks.
Offline
You do have a "{", you're using it for the boundaries of your array.
I'm no C guru but I think what you want to do is something like this:
double x[] = {4, 4.6, 5, 2.3}
int main() {
double y = x[2];
// etc
}
Last edited by Mashi (2008-11-17 19:07:37)
Offline
Stay away from #define for things like this - #define is a preprocessor macro and really shouldn't be used for this purpose.
Mashi is correct, if you want a constant array, define it like so:
const double x[] = {4, 4.6, 5, 2.3};
int main() {
double y = x[2];
// etc
}
-edit- A good source for information on preprocessor directives would be http://www.cplusplus.com/doc/tutorial/preprocessor.html - it's a C++ information site, but the info is pretty well the same for C/C++, as they use very similar preprocessors. -/edit-
Last edited by Cerebral (2008-11-17 19:25:59)
Offline
I know its possible to learn a programming language from entirely free resources, but I would highly recommend picking up a copy of this book: http://www.amazon.com/Programming-Langu … 018&sr=8-1
I found it to be a very concise guide to using the language and has a permanent place in my technical library
Offline
If you really want to do it:
#define X {4, 4.6, 5, 2.3}
int main(void)
{
double x[] = X;
double y;
y = x[2];
return 0;
}
Offline
Thanks guys. I tried Cerebral's code and it works fine.
Offline
Pages: 1