在C和C++里,要尽量避免使用 system("pause")

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://amigniox.blogbus.com/logs/47563613.html

system("pause")

I've never understood why system("PAUSE") is so popular. Sure it will pause aprogram before it exits. This pause is very useful when yourIDE won't waitas you test a program and as soon as the program finished the window closes taking all your data with it.

But using system("PAUSE") islike burning your furniture for heat when you have a perfectly good thermostat on the wall.

Many people, instructors included, for some inexplicable reason think that making a call to the operating system and running a system command totemporarily halt a program is a good thing. Where they get thisidea is beyond me. Reasons:

  • It's not portable. This works only onsystems that havethe PAUSE commandat the system level, like DOS or Windows. But notLinux and most others...

  • It's a very expensive and resource heavy function call.

    It's like using a bulldozerto open your front door. It works, but the key is cleaner, easier,cheaper. What system() doesis:

     

    1. suspend your program

    2. call the operating system

    3. open an operating system shell (relaunches the O/S in asub-process)

    4. the O/S must now find the PAUSE command

    5. allocate the memory to execute the command

    6. execute the command and wait for a keystroke

    7. deallocate the memory

    8. exit the OS

    9. resume your program

    There are much cleaner ways included in the language itself thatmake all this unnessesary.

  • You must include a header you probably don'tneed: stdlib.h or cstdlib

 

It's a bad habit you'll have to break eventually anyway.

Instead, use the functions that are defined natively in C/C++already. So what is it you're trying to do? Wait for a key to bepressed? Fine -- that's called input.So in C, use getchar() instead.In C++, how about cin.get()?All you have to do is press RETURN andyour program continues.

Note: the origin of the article isn't specified.

++
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值