puts()函数和printf函数的区别

puts()函数只用来输出字符串,没有格式控制,里面的参数可以直接是字符串或者是存放字符串的字符数组名。

printf()函数的输出格式很多,可以根据不同格式加转义字符,达到格式化输出。

puts()函数的作用与语句printf("%s\n",s);的作用形同。

例子:

#include<stdio.h>

intmain(void)
{
puts("Helloworldfromputs!");//字符串,最后隐含带有'\0'字符
}
Output
Helloworldfromputs!

main()
{
staticchara[]={'H','I','!','!'};
puts(a);
}
则输出Hi!!烫烫烫烫烫烫烫烫烫烫烫烫dhaklhdwuhdaghdagdak...(后面都是乱码)

原因:a在结尾处缺少一个空字符('\0'),所以它不是一个串,这样,puts()就不知道什么时候停止输出,它将会把a后面内存单元中的内容都打印出,直到它在什么地方碰到了一个空字符为止。


//==============
cathello.c
#include<stdio.h>
intmain(void)
{
printf("helloworld!\n");
}
//========================
gcc-Shello.c-ohello.s生成汇编代码
//========================
cathello.s
//=========================
.file"hello.c"
.section.rodata
.LC0:
.string"helloworld!"
.text
.globlmain
.typemain,@function
main:
leal4(%esp),%ecx
andl$-16,%esp
pushl-4(%ecx)
pushl%ebp
movl%esp,%ebp
pushl%ecx
subl$4,%esp
movl$.LC0,(%esp)
callputs//========这里不是printf
addl$4,%esp
popl%ecx
popl%ebp
leal-4(%ecx),%esp
ret
.sizemain,.-main
.ident"GCC:(GNU)4.1.2(Ubuntu4.1.2-0ubuntu4)"//=======gcc版本
.section.note.GNU-stack,"",@progbits

修改printf()的参数后

//==========================
#include<stdio.h>
intmain(void)
{
printf("helloworld!addr=0x%08x\n",printf);
}
//==========================
gcc-Shello.c
//======================
cathello.s
//===========.file"hello.c"
.section.rodata
.LC0:
.string"helloworld!addr=0x%08x\n"
.text
.globlmain
.typemain,@function
main:
leal4(%esp),%ecx
andl$-16,%esp
pushl-4(%ecx)
pushl%ebp
movl%esp,%ebp
pushl%ecx
subl$20,%esp
movl$printf,4(%esp)
movl$.LC0,(%esp)
callprintf//=================编译后的汇编代码已经是printf了
addl$20,%esp
popl%ecx
popl%ebp
leal-4(%ecx),%esp
ret
.sizemain,.-main
.ident"GCC:(GNU)4.1.2(Ubuntu4.1.2-0ubuntu4)"
.section.note.GNU-stack,"",@progbits
原因:puts()函数的作用与语句printf("%s\n",s);的作用形同。gcc可能对其进行了优化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值