Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I write this if statement with a variable declaration on one line? [duplicate]

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.

like image 759
Zebrafish Avatar asked Sep 01 '17 11:09

Zebrafish


People also ask

How do you write one line in an if statement?

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.

Can you declare variables in an if statement?

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.

Can we write if-else in one line in Python?

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.


2 Answers

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.

like image 189
Passer By Avatar answered Sep 23 '22 22:09

Passer By


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).

like image 27
Martin Bonner supports Monica Avatar answered Sep 21 '22 22:09

Martin Bonner supports Monica