I am new in C programming and trying to figure out some problems encountered. When I wrote
#define N 5
void Sort(int *const array, int N);
the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?
You're using the preprocessor which runs on the raw text of the program before the compiler even sees it. So in this case all occurrences of N (when the N is by itself, not part of another word) get replaced by 5. By the time the program gets to the compiler, due to the preprocessor, all it sees is:
void Sort(int *const array, int 5);
Which is invalid syntax, and that's why you're getting the error.
Either use a different name for the #define, or change your parameter name to any other valid identifier. The latter would look like this:
#define N 5
void Sort(int *const array, int number);
One other option would be to not use variable names in the function prototype:
#define N 5
void Sort(int *const, int);
But then you still have the problem of naming it in the actual function definition.
Note that even just changing the case of the letter (from N to n) would fix it, but don't do that because it might look ambiguous to someone.
If you are using C++, you shouldn't use #define (avoid it as much as you can, because they are bad in myriad ways). You should prefer a const int:
const int N = 5;
You can use this just about anywhere you could use the other, plus it won't break when people try to use that name for themselves, and it won't cause multiple definitions like it would in C (thanks Jens). For example, your original code would have worked if you'd used a constant instead of #define:
const int N = 5;
void Sort(int *const array, int N); // works because N is a real variable
Since the question is tagged as C++, I suggest to stop using #define for the purpose of defining constants:
const int N = 5;
int f(int N); // works
If you're forced to use preprocessor, give your macros long ugly names to avoid name-clashes:
#define YOUR_MEANINGFUL_CONSTANT_NAME_GOES_HERE 5
int f(int N); // works;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With