acmilan作者
9年3个月前修改于 9年3个月前IP:四川
839294
3楼

不违背语言逻辑的做法都是可行的。。。

像是这种情况,就不能用goto。

#include <windows.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
int _tmain(int argc, TCHAR **argv)
{
	if (argc >= 1) goto b;
	int i = 1; // warning & assert fail
	//string s = "aaa"; // compile error
b:
	cout << i << endl;
	return 0;
}
</iostream></string></tchar.h></windows.h>

微软那个可以用goto是因为变量声明和初始化都写在函数开头附近,不存在被跳过的问题。

一般来说,如果你习惯于C89风格的那种变量声明全部写在开头的做法,完全可以随意使用goto。但是如果你习惯于ISO C++风格的那种变量声明写在程序中间的做法,就应该考虑一下其它写法。比如你如果觉得do-while(0)-break太拽,完全可以换一种写法。

	需要清理的资源变量声明;
	{
		不需要清理的变量声明;
		可能失败的操作;
		if (失败) goto 清理;
		// ...
	}
清理:
	if (变量1需要清理)
		清理变量1;
	// ...
评论
文号 / 839294

千古风流
名片发私信
学术分 4
总主题 466 帖总回复 2942 楼拥有证书:进士 学者 笔友
注册于 2009/05/30 21:22:42最后登录 2019/01/31 17:16:38
主体类型:个人
所属领域:无
认证方式:邮箱
IP归属地:0

个人简介

暂未填写
笔记
{{note.content}}
{{n.user.username}}
{{fromNow(n.toc)}} {{n.status === noteStatus.disabled ? "已屏蔽" : ""}} {{n.status === noteStatus.unknown ? "正在审核" : ""}} {{n.status === noteStatus.deleted ? '已删除' : ''}}
  • 编辑
  • 删除
  • {{n.status === 'disabled' ? "解除屏蔽" : "屏蔽" }}
我也是有底线的