无法得到这个问题。 [英] Can't get this Question.

查看:76
本文介绍了无法得到这个问题。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的老师问我们一个听起来很混乱的问题,问题是:



如果关系运算符总是返回0或1,为什么其他值得认为是真的吗?



我发现这个问题有点不对,我想知道这个问题是不是真的错了?如果这个问题出错了,问题应该是什么?

如果问题是对的,那么答案是什么?

谢谢。

解决方案

这个问题是正确的,它应该让你考虑关系运算符以及C / C ++中真与假的实现



在C#和VB中,有一个特定的布尔数据类型: bool ,它只包含两个值: true 并且 false - 并且你不能将它转换为整数并且得到内部值。

C(和派生的C ++)来自它)是不同的:没有布尔数据类型 - 相反,任何零值都是false,任何非零值都是true:所以你可以说

 < span class =code-keyword> while (* myCharPointer)printf(* myCharPointer ++); 

它会将每个字符打印到空终止符。

但是......运算符必须返回一个值:并且在...中关系运算符的情况,例如==,<,>等等,定义是它们返回0(假)或1(真),因为它们必须返回非零值并且一个是一个很好的简单值!



它实际上是一个PITA:如果你的编译器没有发现它,或者你不关心警告,那么这段代码:

  if (myInteger =  666 
{
...
}

总是如此,因为将值666分配给myInteger并将666与零进行比较以确定它是否为真。


My teacher asked us a question which sounds very confusing, the question is:

If a Relational Operator always returns 0 or 1, why are other values considered true?

I found this question little bit wrong, I want to know whether this question is really wrong? If this question is wrong, what should be the question?
And if the question is right, then what will be the answer?
Thank you.

解决方案

The question is right, and it's supposed to make your think about relational operators and the implementation of true and false in C / C++

In C# and VB, there is a specific boolean datatype: bool which contains only two values: true and false - and you can't convert that to an integer and "get at" the internal value.
C (and C++ which is derived from it) is different: there was no boolean datatype - instead any value of zero is false, and any non-zero value is true: so you can say

while(*myCharPointer) printf(*myCharPointer++);

And it will print every character up to the null terminator.
But...operators have to return a value: and in the case of relational operators such as "==", "<", ">", and so forth the definition was that they return 0 (false) or 1 (true) because they have to return a non-zero value and one is a nice simple value!

It's actually a PITA: if your compiler doesn't spot it, or you don't care about warnings, then this code:

if (myInteger = 666)
   {
   ...
   }

Is always true, because assigns the value 666 to myInteger and compares 666 to zero to decide if it is true or not...


这篇关于无法得到这个问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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