double为true / false [英] double as true / false

查看:331
本文介绍了double为true / false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bjarne建议使用if的条件作为范围限制。特别是这个例子。

Bjarne suggests using the condition in if's as scope restriction. In particular this example.

if ( double d = fd()  ) {
   // d in scope here...
}

我是curios如何解释声明的真/假。 >

I'm curios how to interpret the declaration in a true / false sense.


  1. 这是一个声明

  2. 这是一个双重。

编辑:
它在6.3.2.1作为推荐的C ++编程语言。

It's in 6.3.2.1 The C++ programming language as a recommendation.

Edit2:templatetypedefs建议指针,特别是与动态铸造,可能会提供Bjarnes建议的见解。

templatetypedefs suggestion of pointers, in particular with dynamic casts, might give insight to Bjarnes suggestion.

SteveJessop告诉我: - 一个条件不是一个表达式,它也可以是一个声明,使用的值是被计算的值。

SteveJessop tells me: - A condition is not an expression it can also be a declaration, the value used, is the value being evaluated.

推荐答案

您看到的代码是一种用于在中声明变量的专门技术,如果语句。你通常看到这样的:

The code that you're seeing is a specialized technique for declaring variables in if statements. You commonly see something like this:

if (T* ptr = function()) {
    /* ptr is non-NULL, do something with it here */
} else {
    /* ptr is NULL, and moreover is out of scope and can't be used here. */
}

一个特别常见的情况是使用 dynamic_cast 这里:

A particularly common case is the use of dynamic_cast here:

if (Derived* dPtr = dynamic_cast<Derived*>(basePtr)) {
     /* basePtr really points at a Derived, so use dPtr as a pointer to it. *.
} else {
     /* basePtr doesn't point at a Derived, but we can't use dPtr here anyway. */
}

在你的情况下发生的是你声明一个 double if 语句中。 C ++自动将任何非零值解释为true,并将任何零值解释为false。这个代码的含义是declare d 并设置它等于 fd()。如果它是非零, 如果语句。

What's happening in your case is that you're declaring a double inside the if statement. C++ automatically interprets any nonzero value as "true" and any zero value as "false." What this code means is "declare d and set it equal to fd(). If it is nonzero, then execute the if statement."

也就是说,这是一个非常糟糕的主意,因为 double 受到各种舍入错误的影响,在大多数情况下,这些舍入错误会阻止它们为0。这个代码几乎肯定会执行 if 语句的主体,除非函数很好。

That said, this is a Very Bad Idea because doubles are subject to all sorts of rounding errors that prevent them from being 0 in most cases. This code will almost certainly execute the body of the if statement unless function is very well-behaved.

希望这有助于!

这篇关于double为true / false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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