Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a variable inside an if condition?

Tags:

c++

Let's say I have a function MyFunction that returns a value from 0 to 10. 0 indicates a success and nonzero a failure. If I want to display a MessageBox with the value only when it's nonzero I have to do the following:

int e = MyFunction();
if (e != 0) { MessageBox(e); }

If I want to have the variable int e to be local without causing redefinition (because I'm bad at naming or something) I can enclose the whole thing in curly braces and isolate the variable like so:

int e;
{ int e = MyFunction(); if (e != 0) { MessageBox(e); } }

Is it however possible to compress this into a single if statement instead like so:

if (int e = MyFunction() != 0) { MessageBox(e); } //obviously does not work as intended

I know if statements don't really work this way but is it possible to do it anyway by using some c++ magic? It may sound trivial to you guys but I really want to do this. I did search, also asked, but no dice. Thanks!

like image 800
KFA Avatar asked Mar 09 '26 05:03

KFA


1 Answers

You can do it like this:

if(int e = MyFunction())
{
    MessageBox(e);
}

This works because int naturally converts to bool so the if() succeeds when e is any non-zero value (or if it converts to true bool value).

The benefit of this is that you don't litter the surrounding scope with error return values. Though it may not be as immediately obvious to some coders as separating the function call from the test.

like image 139
Galik Avatar answered Mar 12 '26 04:03

Galik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!