Syntax error while using a #define in initializing

2019-03-02 11:12发布

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?

2条回答
趁早两清
2楼-- · 2019-03-02 11:54

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*/
查看更多
女痞
3楼-- · 2019-03-02 12:03

Remove ; after define.

#define TEST 1
查看更多
登录 后发表回答