C++ c++;。可以在不出错的情况下执行此操作:';未在此范围内声明';

C++ c++;。可以在不出错的情况下执行此操作:';未在此范围内声明';,c++,variables,if-statement,declaration,C++,Variables,If Statement,Declaration,c++。有可能这样做吗 if (x>3) int foo=10 else long foo=10 没有错误: 未在此范围中声明 可以,使用或boost::variant std::variant<int, long> foo; if(x > 3) foo = 10; else foo = long(10); 我不知道你为什么要这么做。long保证能够保存所有int值,这样您就可以将foo类型设置为long,并完全避免std::variant。是的

c++。有可能这样做吗

if (x>3)
 int foo=10
else
 long foo=10
没有错误:

未在此范围中声明

可以,使用或
boost::variant

std::variant<int, long> foo;

if(x > 3)
    foo = 10;
else
    foo = long(10);
我不知道你为什么要这么做。
long
保证能够保存所有
int
值,这样您就可以将
foo
类型设置为
long
,并完全避免
std::variant

是的,您可以使用或
boost::variant

std::variant<int, long> foo;

if(x > 3)
    foo = 10;
else
    foo = long(10);

我不知道你为什么要这么做。
long
保证能够保存所有
int
值,因此您只需将
foo
类型设置为
long
,并完全避免
std::variant

不可以,因为变量
x
的作用域位于if块内部,因此您无法从外部看到它:

int main()
{
    if(!x)
        int value = 100;
    else
        double value = 5.57; 

    cout << value << endl; // values is scoped to if statement or else's so it will be destructed

    // this example is like what you have above
    for(;;)
    {
        int a = 77;
        if(a)
            break;
    }

    cout << a << endl; // error a is undeclared identifier

    return 0;
}
intmain()
{
如果(!x)
int值=100;
其他的
双值=5.57;

cout否您不能,因为变量
x
的作用域位于if块内部,因此您无法从外部看到它:

int main()
{
    if(!x)
        int value = 100;
    else
        double value = 5.57; 

    cout << value << endl; // values is scoped to if statement or else's so it will be destructed

    // this example is like what you have above
    for(;;)
    {
        int a = 77;
        if(a)
            break;
    }

    cout << a << endl; // error a is undeclared identifier

    return 0;
}
intmain()
{
如果(!x)
int值=100;
其他的
双值=5.57;

CUTE你想做什么?有什么具体问题吗?请显示产生错误的代码。你不能做你建议的。变量的范围是<>代码>如果和 EX/COD>。变量在C++中的每个范围内都是强类型的。你试图打破它。这可能是个问题。无法在if语句/else语句内声明变量,并在该语句外的代码中使用它。XY问题再次出现。更大的问题是什么?你想用它实现什么?你想做什么?有一个特定的问题吗?请显示生成该错误的代码。你不能执行你建议的操作。variab的范围LES是<>代码> 和 EX/<代码>。变量在C++中的每个作用域内都是强类型的。你试图打破它。这可能是一个问题。同样,你不能在if语句/EL语句中声明变量,并将其用在Stest.XY问题之外的代码中。更大的图片是什么??你想用它实现什么?回答得好,学到了一些东西。不完全是他问的,但可能是他的意思。回答得好,学到了一些东西。不完全是他问的,但可能是他的意思。