关于函数指针被赋值时候 右值与左值不一样的问题

tianziyulu 2006-05-29 04:18:11
详细描述在代码注释中

#include "stdio.h"

typedef int (*PNFV)() ;

int temp1()
{
return printf( "temp1\n" );
}

int temp2()
{
return printf( "temp2\n" );
}

int temp()
{
static PNFV temp = 0;
if ( temp == 0 )
{
temp = temp1; \\此处不管是 temp=&temp1 还是temp = \\ = temp1,temp的值都是一样,但跟temp1不同?何解??
temp();
}
else if ( temp == temp1 )
{
temp = &temp2;
\\同上;
temp();
}


return 0;
}

int main()
{
printf( "The address of temp1 is %x\n", temp1 );
printf( "The address of temp2 is %x\n", temp2 );
temp();
printf( "The address of temp is %x\n", temp );
temp();
printf( "The address of temp is %x\n", temp );
return 0;
}
...全文
141 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
hslinux 2006-05-29
  • 打赏
  • 举报
回复
The address of temp1 is 40100a
The address of temp2 is 40100f
temp1
The address of temp is 401005
temp2
The address of temp is 401005

楼主的代码在VC6.0里运行的结果,不知道这个是不是楼主想要的结果。
temp()里与temp()同名的变量把temp()屏蔽了,局部变量优先于全局变量.
goodluckyxl 2006-05-29
  • 打赏
  • 举报
回复
temp 你定义的有问题
你的内部变量和自身所在的函数名字相同
内部static作用范围并非全局
而函数名字temp地址却是全局可见
所以在main中的temp永远为temp函数的地址
#include <stdio.h>
#include <stdlib.h>
#include "stdio.h"

typedef int (*PNFV)() ;
static PNFV tem = 0;
int temp1()
{
return printf( "temp1\n" );
}

int temp2()
{
return printf( "temp2\n" );
}

int temp()
{

if ( tem == 0 )
{
tem = temp1; //此处不管是 temp=&temp1 还是temp = \\ = temp1,temp的值都是一样,但跟temp1不同?何解??
tem();
}
else if ( tem == temp1 )
{
tem = &temp2;
//同上;
tem();
}


return 0;
}

int main()
{
printf( "The address of temp1 is %x\n", temp1 );
printf( "The address of temp2 is %x\n", temp2 );
temp();
printf( "The address of temp is %x\n", tem );
temp();
printf( "The address of temp is %x\n", tem );
return 0;
}
gudulyn 2006-05-29
  • 打赏
  • 举报
回复
不用说了

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧