有关问题:++运算符在macro和function中的不同
问题:++运算符在macro和function中的不同一个小实验,编译链接环境用的是VC++6.使用function实现版本的_tou
问题:++运算符在macro和function中的不同
一个小实验,编译链接环境用的是VC++6.
使用function实现版本的_toupper(),代码如下:
C/C++ code#include <ctype.h>[b]#undef _toupper [/b] #include <stdio.h> void main() { int c = 'm'; c = _toupper(c++); printf("c = %c\n", c);}
此时的打印结果为
c = M使用macro实现版本的_toupper(),代码如下:
C/C++ code#include <ctype.h>//#undef _toupper #include <stdio.h> void main() { int c = 'm'; c = _toupper(c++); printf("c = %c\n", c);}
此时的打印结果为
c = N从ctype.h中可知macro版本的_toupper()定义如下:
C/C++ code#define _toupper(_c) ( (_c)-'a'+'A' )
两个结果不同。
c = _toupper(c++); 在函数版本时,c先传进函数,然后自己自增1,这样可以理解;但在宏版本时,( (_c)-'a'+'A' )中(_c)的值为什么是c自增1之后的值了???
[解决办法]VC:
宏替换后变成了:c = (c++) -'a'+'A';
问题出现在你在=号的两端都使用了c.
先看下面的:
int n = (c++) -'a'+'A';
编译器把c的值放到n中,然后-'a'+'A',最后c增加1
对于c = (c++) -'a'+'A';
在c中-'a'+'A',最后c增加1
[解决办法]比如:int i=5;i=i++;最后i==6而不==5.
如果换成int j=i++;则j==5.
[解决办法]楼主您好我来解释您的问题:
用函数版本 等价于我下面的代码
#include <ctype.h>
#undef _toupper #include <stdio.h>
void main()
{
int c = 'm';
int ctemp;
ctemp = c++;
c = _toupper(ctemp);
printf("c = %c\n", c);
}
而用宏的话类等价于我下面的代码:
#include <ctype.h>
#undef _toupper #include <stdio.h>
void main()
{
int c = 'm';
int ctemp;
ctemp = c;
c = _toupper(ctemp);
c++;
printf("c = %c\n", c);
}
呵呵,看到为什么不一样了吧,还没完 ,如果使用下面的宏 将和你用函数是一样的
#define _toupper(c) \
({\
typeof(c) __c = c;\
__c - 'c'+'A';\
})
我用的是语句块返回值机制,和逗号表达式类似 只不过它是分号 并两端有({ 和 }) 小括号大括号都不能省哦 要不就不能返回__c - 'c'+'A'的值了
[解决办法] 补充下怕我些的不够清晰
ctemp = c++;
c = _toupper(ctemp);
也就是
ctmp = c;
c = c +1;//所以它字增是没用的 后面的函数重新赋值给了c 而函数的参数是ctemp = c,c未字增前的赋值
c = _toupper(ctemp)