DEV Community

Swastik Baranwal
Swastik Baranwal

Posted on

6 2

Modern C++: Temp Vars in If/Switch

Following my series from less known features of Modern C++.

This feature is small and minor one so this article is small but an important for sure.

From C++ 17 you can declare temporary variables on if and switch statements just like loops. As the variables are temporary, you can't access those variables as they are only declared in the if or switch block.

If Statement



#include <iostream>

int main()
{
  if (int i = 0; i > 0)
    {
      std::cout << "i is positive" << std::endl;
    }
  else if (i < 0)
    {
      std::cout << "i is negative" << std::endl;
    }
  else
    {
      std::cout << "i is zero" << std::endl;
    }
 // std::cout << i << std::endl;    // i will not be available here
}


Enter fullscreen mode Exit fullscreen mode

Switch Statement



#include <iostream>

int main()
{
  switch (int i = 0)
    {
    case 0:
      std::cout << "i is negative";
      break;

    case 1:
      std::cout << "i is one";

    default:
      std::cout << "invalid";
      break;
    }
  //std::cout << i << std::endl;        // i will not be available here
}


Enter fullscreen mode Exit fullscreen mode

If we comment out the last line of both of the examples then an error will be raised.



main.cpp: In function ‘int main()’:
main.cpp:26:17: error: ‘i’ was not declared in this scope
    std::cout << i << std::endl;        // i will not be available here


Enter fullscreen mode Exit fullscreen mode

This feature is useful when you need to temporary declare variables for checking and minor comparisons.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (2)

Collapse
 
mabla0531 profile image
Matthew Bland

Now this is cool.

Collapse
 
delta456 profile image
Swastik Baranwal

Thanks! More coming soon :)

Also my Code for my Articles series is now at github.com/Delta456/modern_cpp_series

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay