数组堆栈的宏????
#include<stdio.h>数组堆栈的宏 c
#include<stdlib.h>
#include <assert.h>// 断言
//下面是数组堆栈的宏 函数依次是 判空 判满 压入 置顶 输出
#define generic_stack(stack_type,suffix,stack_size) \
static stack_type stack##suffix[stack_size]; \
static int top_element##suffix=-1; \
int is_empty##suffix() \
{ \
return top_element##suffix==-1; \
} \
void is_full##suffix() \
{ \
return top_element##suffix==stack_size-1; \
} \
int push##suffix(stack_type value) \
{ \
assert(!is_full##suffix()); \
top_element##suffix+=1; \
stack##suffix[top_element##suffix]=value; \
} \
void pop##suffix() \
{ \
assert(!is_empty##suffix()); \
top_element##suffix-=1; \
} \
stack_type top##suffix() \
{ \
assert(!is_empty##suffix()); \
return stack##suffix[top_element##suffix]; \
}
void main()
{
generic_stack(int,_int,10);
push_int(5);//输入5
push_int(10);
push_int(20);
while(!is_empty_int())
{
printf("%d\n",top_int());//输出
pop_int();
}
}
//通不过编译器啊!!!!!!!
assert(!is_full##suffix()); \
top_element##suffix+=1; \
stack##suffix[top_element##suffix]=value; \
} \
void pop##suffix() \
{ \
assert(!is_empty##suffix()); \
top_element##suffix-=1; \
} \
stack_type top##suffix() \
{ \
assert(!is_empty##suffix()); \
return stack##suffix[top_element##suffix]; \
}
generic_stack(int,_int,10);
void main()
{
//generic_stack(int,_int,10);
push_int(5);//输入5
push_int(10);
push_int(20);
while(!is_empty_int())
{
printf("%d\n",top_int());//输出
pop_int();
}
}
[解决办法]
没有尝试修改楼主的代码,但是看一遍楼主代码之后发现一个重要的影响编译能否通过的问题:
1.generic_stack这个宏涉及到函数的定义,因此不能在局部空间中用,否则语法上肯定不能通过(C
语言不支持嵌套函数定义)
2.对generic_stack的调用,最好不要加分号,否则可能引起别的语法错误。
还有一点,直接在这里看不出来,但是楼主一定要小心宏定义后面的\,这个符号后面必须马上回车,不能加任何一个字符,空格 tab都不行。
最后在程序设计方面,我认为楼主对pop的定义理解得不是很好,push和pop操作一般是成对的,
不应该pop之后没有修改栈顶。
以后楼主调试这种有大量宏定义的代码,如果编译不通过,就如楼上赵老师所说,
先将代码编译成.i格式,也就是宏展开之后的C代码,然后再在这个文件中看你的
宏被编译器展开成什么样,这样修改错误就方便很多了。