C++ 如何在 if() 语句中声明变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14620898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:31:32  来源:igfitidea点击:

How does one declare a variable inside an if () statement?

c++

提问by x-x

Possible Duplicate:
Declaring and initializing a variable in a Conditional or Control statement in C++

可能的重复:
在 C++ 中的条件或控制语句中声明和初始化变量

Instead of this...

而不是这个...

int value = get_value();
if ( value > 100 )
{
    // Do something with value.
}

... is it possible to reduce the scope of valueto only where it is needed:

...是否可以将的范围缩小到仅需要的地方:

if ( int value = get_value() > 100 )
{
    // Obviously this doesn't work. get_value() > 100 returns true,
    // which is implicitly converted to 1 and assigned to value.
}

采纳答案by Rapptz

If you want specific scope for value, you can introduce a scope block.

如果你想要特定的值范围,你可以引入一个范围块。

#include <iostream>

int get_value() {
    return 101;
}

int main() {
    {
        int value = get_value();
        if(value > 100)
            std::cout << "Hey!";
    } //value out of scope
}

回答by Lightness Races in Orbit

Can you declare a variable and compare it within the if()statement? No.
Can you declare a variable and compare it in such a way that the scope is tightly-bound to the if()block? Yes!

你能声明一个变量并在if()语句中进行比较吗?号
你可以声明一个变量,并以这样的方式,范围紧密绑定到比较if()块?是的!



You can eitherdeclare a variable:

您可以要么声明一个变量:

if (int x = 5) {
   // lol!
}

oryou can do thingswith one:

或者你可以用一个来做

int x = foo();
if (x == 5) {
   // wahey!
}

You can't do both!

你不能两者兼得!



You cancheat a little where the only thing you need to do is compare with true, because the declaration itself evaluates to the value of the new object.

在您唯一需要做的就是与 比较的地方,您可以稍微作弊true,因为声明本身会评估新对象的值。

So, if you have:

所以,如果你有:

int foo()
{
   return 0;
}

Then this:

然后这个:

if (int x = foo()) {
    // never reached
}

is equivalent to:

相当于:

{
   int x = foo();
   if (x) {
       // never reached
   }
}


This final syntax, using a standalone scope block, is also your golden bullet for more complex expressions:

这个使用独立作用域块的最终语法也是更复杂表达式的黄金子弹:

{
   int x = foo();
   if (x > bar()) {
       // wahooza!
   }
}

回答by Peter Wood

Put it in a function:

把它放在一个函数中:

void goodName(int value) {
    if(value > 100) {
        // Do something with value.
    }
}

//...
    goodName(get_value());

回答by jxh

How about using forinstead?

如何使用for呢?

for (int value = get_value(); value > 100; value = 0) {
    //...
}

If you want to go C++11 on it, you can use a lambda:

如果你想使用 C++11,你可以使用 lambda:

[](int value = get_value()) {
    if (value > 100) {
        //...
        std::cout << "value:" << value;
    }
}();

回答by yumaikas

Or you could just add an extra set of braces for a nested scope, although it's not exactly pretty:

或者您可以为嵌套范围添加一组额外的大括号,尽管它并不完全漂亮:

{
    int value = get_value();
    if ( value > 100 )
    {
        // Do something with value.
    }   
}
//now value is out of scope

回答by Nawaz

You can write a small function which can do the comparison for you and return the value the if comparison returns true, else return 0to avoid executing the ifblock:

您可以编写一个小函数,它可以为您进行比较并返回 if 比较返回 true 的值,否则返回0以避免执行if块:

int greater_than(int right, int left)
{
   return left > right ? left : 0;
}

Then use it as:

然后将其用作:

if ( int value = greater_than(100, get_value()))
{
      //wow!
}

Or you can use foras other answer said. Or manually put braces to reduce the scope of the variable.

或者你可以for像其他答案说的那样使用。或者手动放置大括号以减少变量的范围。

At any rate, I would notwrite such code in production code.

无论如何,我也不会写在产品代码这样的代码。

Don't write code for machines. Write code for humans. Machines will understand anything as long as you follow their grammar; humans understand what is readable to them. So readability should be your priority over unnecessaryscoping.

不要为机器编写代码。为人类编写代码。只要你遵循它们的语法,机器就会理解任何东西;人类理解什么对他们来说是可读的。因此,可读性应该优先于不必要的范围。

回答by Steve Jessop

In this particular case, you can bodge it:

在这种特殊情况下,你可以bodge它:

if (int value = (get_value() > 100 ? get_value() : 0)) {
    ...
}

I don't really recommend it, though. It doesn't work for all possible tests that you might want to perform, and it calls get_value()twice.

不过我真的不推荐它。它不适用于您可能想要执行的所有可能的测试,并且它会调用get_value()两次。