Syntax error while using a #define in initializing an array, and as arguments to a function in C? [closed]

霸气de小男生 提交于 2020-01-11 12:34:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!