求教,C语言中的!在if语句中是什么作用。

wsfzk 2010-10-22 11:59:53
最近学习到了链表,大概意思弄了个差不多,在实际应用中碰到了问题。于是我就把书上的一道例题的源代码整个打了出来,发现一句代码无法理解,请各位老师指教。

LISTPTR add_to_list(int ch,LISTPTR first)
{
LISTPTR new_rec=NULL;//声明一个新指针,用来存储新节点
LISTPTR tmp_rec=NULL;
LISTPTR prev_rec=NULL;
new_rec=(LISTPTR)malloc(sizeof(LIST));//为新节点分配内存
if(!new_rec)//就是这一句,前面有一个!号,如果把它去掉程序就无法正常运行
{
printf("\nUnable to allocale memory!\n");
exit(1);
}
new_rec->ch=ch;
new_rec->next_rec=NULL;
if(first==NULL)
{
first=new_rec;
new_rec->next_rec=NULL;
}
else
{
if(new_rec->ch < first->ch)
{
new_rec->next_rec=first;
first=new_rec;
}

else
{
tmp_rec=first->next_rec;
prev_rec=first;
if(tmp_rec==NULL)
{
prev_rec->next_rec=new_rec;
}
else
{
while((tmp_rec->next_rec != NULL))
{
if(new_rec->ch < tmp_rec->ch)
{
new_rec->next_rec=tmp_rec;
if(new_rec->next_rec != prev_rec->next_rec)
{
printf("ERROR");
getc(stdin);
exit(0);
}
prev_rec->next_rec=new_rec;
break;
}
else
{
tmp_rec=tmp_rec->next_rec;
prev_rec=prev_rec->next_rec;
}
}
if(tmp_rec->next_rec==NULL)
{
if(new_rec->ch < tmp_rec->ch)
{
new_rec->next_rec=tmp_rec;
prev_rec->next_rec=new_rec;
}
else
{
tmp_rec->next_rec=new_rec;
new_rec->next_rec=NULL;
}
}
}
}
}
return(first);
}
...全文
318 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wsfzk 2010-10-25
  • 打赏
  • 举报
回复
多谢楼上朋友的热心解答,由此可见在CSDN中朋友们都十分热心,能在这样的环境下学习,真的是非常幸福的。
大石头1987 2010-10-22
  • 打赏
  • 举报
回复
if(!new_rec)//就是这一句,前面有一个!号,如果把它去掉程序就无法正常运行
{
printf("\nUnable to allocale memory!\n");
exit(1);
}

这句是用来判断new_rec的结果,看是真还是假!
你把它去了的话,就不是执行{}里面的语句了!
小魔菇 2010-10-22
  • 打赏
  • 举报
回复
if(!new_rec)//就是这一句,前面有一个!号,如果把它去掉程序就无法正常运行
{
printf("\nUnable to allocale memory!\n");
exit(1);
}

是啊 如果new_rec为NULL的话 程序就应该正常退出
在正常情况下new_rec不是空的 你如果去掉了! 程序就退出了
Sou2012 2010-10-22
  • 打赏
  • 举报
回复
if (true)
{

}
else
{
// false
}
try325 2010-10-22
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ouyh12345 的回复:]


如果new_rec是NULL,则!new_rec为真
[/Quote]
逻辑非
ouyh12345 2010-10-22
  • 打赏
  • 举报
回复

如果new_rec是NULL,则!new_rec为真
Jim_King_2000 2010-10-22
  • 打赏
  • 举报
回复
在C语言中,基本上,!的作用就是把值0变成1,把任何非0值变成0。
有一个小技巧用来实现当x为0的时候,输出0;当x不为0的时候输出1.
!!n

在C++语言中,除了上述规则之外,还能把bool类型的true变成false,false变成true。
wsfzk 2010-10-22
  • 打赏
  • 举报
回复
多谢各位老师的指点

33,322

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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