C++ if语句
C++ if语句
语法
if(xxx)
true_branch_statement
else
false_branch_statement
注意:这里的是statement。
而if语句也是statement,所以我们经常见到以下写法
if(condition_0)
statement_0
else if(condition_1)
statement_1
else
statement_2
这里就要解释一下else if并不是C++的语句,这里是if(condition_0)的else分支的语句是if(condition_1)的if语句。最后else分支是if(condition_1)的分支。
换个写法:
if(condition_0)
{
statement_0
}
else
{
if(condition_1)
{
statement_1
}
else
{
statement_2
}
}
所以个人之前对if语句的理解全错了。
写作缘由
在看libstdc++的format源码
template<typename _Tp, typename... _OtherArgs>
constexpr void
_M_parse_format_spec(size_t __id)
{
if (__id == 0)
{
formatter<_Tp, _CharT> __f;
this->_M_pc.advance_to(__f.parse(this->_M_pc));
}
else if constexpr (sizeof...(_OtherArgs) != 0)
_M_parse_format_spec<_OtherArgs...>(__id - 1);
else
__builtin_unreachable();
}
这最后的else是if constexpr (sizeof...(_OtherArgs) != 0)的分支。
浙公网安备 33010602011771号