Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Why can't variables be declared in a switch statement

Why can't variables be declared in a switch statement

Scheduled Pinned Locked Moved C / C++ / MFC
c++question
2 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    tracyhe123
    wrote on last edited by
    #1

    I've always wondered this -why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work

    L 1 Reply Last reply
    0
    • T tracyhe123

      I've always wondered this -why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You can, you just need to put them, and the code that uses them inside curly braces, thus:

      switch (number)
      {
      case 1:
      {
      int i; // local to only this case statement
      }
      }

      Variables not inside such a block are considered to have the scope of the entire switch block. But if they are declared in a single case statement there is a possibility that they would not get initialised safely. To make a variable available to multiple case statements it must be declared before the switch.

      1 Reply Last reply
      0
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • World
      • Users
      • Groups