我的CPP之路

路漫漫其修远兮
随笔 - 42, 文章 - 0, 评论 - 16, 引用 - 0
数据加载中……

&和&&

最近在看《The C Programming Language 2nd Ed》,把其中自己认为值得注意的地方记下来。小弟水平有限,若哪个地方理解错了还请各位GGJJ指出。先谢谢了。

<<TCPL 2ED>>

P46 倒数第二段 (2.9 Bitwise Operators)

One must distinguish the bitwise operators & and | from the logical operators && and ||, which imply left-to-right evaluation of a truth value. For example, if x is 1 and y is 2, then x & y is zero while x && y is one.

---------

1 & 2      就是   01 & 10 -> 00
1 && 2   就是   true && true -> true
无论什么语言都要注意位操作符和逻辑与或的区别。
用程序验证一下,gcc 3.4.2,^_^

#include <stdio.h>

int main() {
    
int x = 1, y = 2;
    printf(
"x=1, y=2\n");
    printf(
"x & y : %d : %s\n", x & y, x & y ? "TRUE" : "FALSE");
    printf(
"x && y : %d : %s\n", x && y, x && y ? "TRUE" : "FALSE");
}

输出结果:
x=1, y=2
x & y : 0 : FALSE
x && y : 1 : TRUE

posted on 2007-12-14 12:53 yanvenhom 阅读(502) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理