我可以在一行中使用变量声明来编写这个if语句吗? [英] Can I write this if statement with a variable declaration on one line?

查看:75
本文介绍了我可以在一行中使用变量声明来编写这个if语句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法将它放在一行上?

I was wondering if there was a way to put this on one line?

if (auto r = getGlobalObjectByName(word)) r->doSomething; // This works fine

if (!auto r = getGlobalObjectByName(word)) r->doSomething; // Says "expected an expression"

if (auto r = getGlobalObjectByName(word) == false) r->doSomething; // Also doesn't work.

我也尝试用额外的括号围绕它,但这似乎不起作用。我发现这在一行上非常方便。

I also tried surrounding it with extra brackets, but that doesn't seem to work. I find this really convenient doing it on one line.

推荐答案

从C ++ 17开始,你可以使用初始化if语句

Since C++17 you can use an initializer if-statement:

if (auto r = getGlobalObjectByName(word); !r) r->doSomething;

语义为:

if (init-statement; condition) statement

唯一的区别是traditionalif语句是 init-statement ,它初始化块作用域中的变量,类似于for循环。

The only difference from the "traditional" if-statement is the init-statement, which initializes a variable in the block scope, similar to for-loops.

这篇关于我可以在一行中使用变量声明来编写这个if语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆