不同开关情况下的c ++访问变量 [英] c++ access variable from different switch case

查看:65
本文介绍了不同开关情况下的c ++访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建Win32应用程序,并在WM_CREATE开关的情况下初始化了状态栏宽度变量.

I'm creating a win32 application and initialized my statusbar width variables in my WM_CREATE switch case.

case WM_CREATE:
  {
    int statwidths[] = { 200, -1 };
  }
  break;

我想在WM_SIZE开关的情况下访问statwidths [0],因为该数字将用于确定程序中其余窗口的大小.

I would like to access statwidths[ 0 ] in my WM_SIZE switch case as that number will be used to determine the size of the rest of my windows in my program.

case WM_SIZE:
  {
    int OpenDocumentWidth = statwidths[ 0 ];
  }
  break;

有没有办法做到这一点?它们都在同一文件的同一switch语句中.

Is there a way to do this? They are both in the same switch statement in the same file.

推荐答案

如果它们都在同一switch语句中,则绝对不会.考虑

If these are both in the same switch statement then, absolutely not. Consider

switch (n) {
    case 1: {
    }
    case 2: {
    }
}

只有在n为1的情况下,在1范围内发生的情况.如果我们在那里声明一个变量,然后以n = 2调用此代码,则不会声明该变量.

What happens in the case 1 scope only happens when n is 1. If we declare a variable there and then we call this code with n=2, the variable is not declared.

int n;
if(fileExists("foo.txt"))
    n = 2;
else
    n = 1;
switch (n) {
    case 1: {
        ostream outfile("foo.txt");
        ...
        break;
    }
    case 2: {
        // if outfile were to be initialized as above here
        // it would be bad.
    }
}

您可以在开关外部声明变量,但是除非开关位于循环内,否则您不应该假定先前的情况已经完成.

You can declare the variable outside the switch but you should not then assume the previous case has done its thing unless the switch is inside a loop.

当,上次我尝试着点燃它.

Dang, last time I try to do this on a kindle.

这篇关于不同开关情况下的c ++访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆