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.
One-line if-else statements should only be used with simple expressions (identifiers, literals, and operators). They should not be used with longer statements. This is to preserve the readability and expressibility of the code. So think twice before breaking your Python if-else on one line.
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
Python If Statement In One Line In Python, we can write “if” statements, “if-else” statements and “elif” statements in one line without worrying about the indentation. In Python, it is permissible to write the above block in one line, which is similar to the above block.
Since C++17 you can use an initializer if-statement:
if (auto r = getGlobalObjectByName(word); !r) r->doSomething;
The semantics are:
if (init-statement; condition) statement
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 you have C++17, use the if (init statement; condition)
form. If not, you have three choices:
Stop trying to keep this all on one line. For example:
auto r = getGlobalObjectByName(word); if (!r) r->doSomething();
Use an else
:
if (auto r = getGlobalObjectByName(word)) {} else r->doSomething();
(Note that this requires that r
is a smart pointer with very strange semantics for the operator bool()
function. OTOH, I assume this is actual a short piece of example code, rather than your actual code).
I think I would only use the else
form if it was really important to keep everything on one line (to preserve a tabular formatting of the code for example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With