C语言函数内部可以使用typedef么?
本人C语言初学,在实现行编辑程序的时候遇到了这个问题:
我实现了一个栈,栈内用SElemType作为栈的元素的类型,具体是什么
类型要在用到栈的时候用typedef定义。
可是我在一个程序中想用两种不同的SElemType,我现在在主函数之外,
定义了一个typedef char SEelmType;主函数内部的某一段代码我想用
一个新的栈,里面的元素类型我想用float,请问SElemType可以重新定义么?
如果在函数体内内部重新用typedef定义,会造成什么后果?
请各位赐教啊……
下面是我的代码:
各位请麻烦指出我的代码的不足之处,万分感谢
- C/C++ code
#ifndef _TYPE_SELEMTYPE#define _TYPE_SELEMTYPE typedef char SElemType;#endiftypedef SElemType * ElemLink;#include <stdlib.h>#include <stdio.h>#include <string.h>#include "../SqStack_use.h" //栈的存储结构#include "../SqStack_ops.c" //栈的基本操作//Status 在SqStack_use.h文件中有定义Status IsParentheses ( char left, char right ); //判断是否匹配Status parenthesesMatch ( char *str );Status parenthesesMatch ( char *str ){ SqStack S; SElemType e; ElemLink p; int len; int i; InitStack_Sq(&S); //此函数在SqStack_ops.c中 len = strlen(str); p = NULL; for ( i=0; i<len; i++) { Push_Sq(&S,*(str+i)); if (p!=NULL && IsParentheses(*p, *(S.top-1)) == YES) { Pop_Sq(&S, &e); Pop_Sq(&S, &e); } p = S.top-1; } if (StackEmpty_Sq(S) == YES) return YES; else return NO;}Status IsParentheses ( char left, char right ){ if (left=='(' && right==')') return YES; else if (left=='[' && right==']') return YES; else if (left=='{' && right=='}') return YES; else return NO;}int main ( int argc, char *argv[] ){ char str[20]; do { printf ( "==========================\n" ); printf ( "intput some parentheses(input one char to exit):\n" ); scanf("%s", str); if (strlen(str) == 1) break;#ifdef _TYPE_SELEMTYPE typedef float SElemType; SElemType num = 100.01; printf ( "num is :%f\n" , num);#endif//我这样用了,不知道对不对,但是编译通过了,请各位指教啊 if (parenthesesMatch(str) == YES) printf ( "parentheses matching! congratulations!\n" ); else printf ( "sorry parentheses not matching!\n" ); } while (1); return EXIT_SUCCESS;}[解决办法]
用一个代码段生成不同实际代码是泛型编程的基础思想,你可以将你的堆栈代码放在一个文件中,用ifdef宏定义来区别不同的数据类型,在用到堆栈代码时用#define来生成不同的定义。和你现在的使用方式差不多。
[解决办法]
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct example_st { int what_the_fuck_are_you_doing; int what_the_fuck_are_you_saying; int what_the_fuck_are_you_playing;}*example_t;example_t init_example() { example_t p = (example_t)malloc(sizeof(struct example_st)); if (p == NULL) { return NULL; }#define VARIABLE(last_word) p->what_the_fuck_are_you_##last_word VARIABLE(doing) = 0; VARIABLE(saying) = 1; VARIABLE(playing) = 2;#undef VARIABLE return p;}int main(int argc, char* const argv[]) { example_t p = init_example(); if (p) { free(p); } return 0;}