Home c++ Initialization inside if

Initialization inside if

Author

Date

Category

In the 17 standard, it is possible to initialize the variable inside the IF condition (init; Condition)
So I can do so
if (int i = 12; d & lt; i) {} or so if (int i, b = 10; i == b) {}
But how to initialize some variables of different types?


Answer 1

The answer is the same as for multiple ads in for : C++, more than one ad in the expression of the initialization of the for

elegant way there is no, but someone can like the option with Structured Binding

if (auto [a, b] = std :: make_tuple (4, 3.14); a == b)
 STD :: COUT & LT; & LT; "Yay! Pi is" & lt; & lt; A & LT; & LT; "!" & lt; & lt; STD :: ENDL;
ELSE.
 STD :: COUT & LT; & LT; "NAY ... PI IS NOT" & LT; & LT; A & LT; & LT; "..." & lt; & lt; STD :: ENDL;

Answer 2, Authority 500%

well, like honey, so a spoon …
Or “give the water to drink, otherwise I want to – even spend nowhere!” …

Use the structure, for example:

if (struct {int i; double d;} x = {5, 4.5}; xi & gt; 5 & amp ; & amp; xd & lt; 4)
{
}

Update
Why am I not a supporter of the use of fragile binding … because in size we have about the same, but by type …

Compare, for example :

if (auto [a, b] = make_tuple (1, "ddd"); a & gt; 0)
{
  COUT & LT; & LT; TypeID (a) .name () & lt; & lt; Endl;
  COUT & LT; & LT; Typeid (b) .name () & lt; & lt; Endl;
}
if (struct {double a; string b;} x = {1, "ddd"}; x.a & gt; 0)
{
  COUT & LT; & LT; Typeid (X.A) .name () & lt; & lt; Endl;
  COUT & LT; & LT; Typeid (X.B) .name () & lt; & lt; Endl;
}

Here you need to accurately imagine exactly what exactly and how initialized – say, do not forget to add to 1 point, or s to "DDD"


Answer 3, Authority 100%

What would do the child who would do … it was long ago in 199 …

// g ++ -wall -std = C++ 98 if_pr.cpp
# INCLUDE & LT; IOSTREAM & GT;
# DEFINE IF (A, B, C, D) {A {if (b) {C} else {D}}}
Int F (void) {
 If (int x = 0; int y = 1; int z = 2; int v = x + y + z;, V & gt; 0,
  RETURN V;
  Return 0;)}
INT MAIN () {
 STD :: COUT & LT; & LT; "f =" & lt; & lt; f () & lt; & lt; "\ n";
}

it’s just a joke …

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions