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.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

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

Okay