问题
Using a #define while initializing an array
#include <stdio.h>
#define TEST 1;
int main(int argc, const char *argv[])
{
int array[] = { TEST };
printf("%d\n", array[0]);
return 0;
}
compiler complains:
test.c: In function ‘main’:
test.c:7: error: expected ‘}’ before ‘;’ token
make: *** [test] Error 1
Using a #define as functional input arguments
#include <stdio.h>
#define TEST 1;
void print_arg(int arg)
{
printf("%d", arg);
}
int main(int argc, const char *argv[])
{
print_arg(TEST);
return 0;
}
compiler complains:
test.c: In function ‘main’:
test.c:12: error: expected ‘)’ before ‘;’ token
make: *** [test] Error 1
How does one solve these two problems? I thought C simply does a search and replace on the source file, replacing TEST
with 1
, no?
回答1:
The problem is because there is semicolon in your #define TEST 1;
.
With this, the program translates to:
int array[] = { 1; }; /*this is illegal!*/
Remedy: remove it so it looks like:
#define TEST 1
which translates to:
int array[] = {1}; /*legal*/
回答2:
Remove ; after define.
#define TEST 1
来源:https://stackoverflow.com/questions/14800493/syntax-error-while-using-a-define-in-initializing-an-array-and-as-arguments-to