关于<<和>>运营商 [英] regarding << and >> operators

查看:83
本文介绍了关于<<和>>运营商的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include< stdio.h>

int main(void){

printf("%d%d \ n",32<< 1 ,32<< 0);

printf("%d%d \ n",32<<< -1,32<< -0);

< ----------------------------------见这里

printf( %d%d \ n,32>> 1,32>> 0);

printf("%d%d \ n",32>> - 1,32>> -0);

< ------------------------------ ----和这里


返回0;

}


$ make

gcc -Wall -g -o test test.c

test.c:在函数`main'':

test.c:4:警告:左移计数是否定的

test.c:6:警告:右移计数为负

$ ./test

64 32

0 32(1)

16 32

0 32(2)


为什么打印0( 1)和(2)??

#include<stdio.h>
int main(void){
printf("%d %d\n",32<<1,32<<0);
printf("%d %d\n",32<<-1,32<<-0);
<----------------------------------see here
printf("%d %d\n",32>>1,32>>0);
printf("%d %d\n",32>>-1,32>>-0);
<----------------------------------and here

return 0;
}

$ make
gcc -Wall -g -o test test.c
test.c: In function `main'':
test.c:4: warning: left shift count is negative
test.c:6: warning: right shift count is negative
$ ./test
64 32
0 32 (1)
16 32
0 32 (2)

Why 0 is printed in (1) and (2) ??

推荐答案

make

gcc -Wall -g -o test测试.c

test.c:在函数`main'':

test.c:4:警告:左移计数为负

test.c:6:警告:右移计数为负
make
gcc -Wall -g -o test test.c
test.c: In function `main'':
test.c:4: warning: left shift count is negative
test.c:6: warning: right shift count is negative


./ test

64 32

0 32(1)

16 32

0 32(2)


为什么在(1)和(2)中打印0 )??

./test
64 32
0 32 (1)
16 32
0 32 (2)

Why 0 is printed in (1) and (2) ??


文章< 11 ********************** @ m7g2000cwm.googlegroups。 com>,

onkar< on ******* @ gmail.comwrote:
In article <11**********************@m7g2000cwm.googlegroups. com>,
onkar <on*******@gmail.comwrote:

printf("%d% d\\\
",32 LT;< -1,32<< -0);
printf("%d %d\n",32<<-1,32<<-0);


printf("%d%d \ n",32>> -1,32>> -0);
printf("%d %d\n",32>>-1,32>>-0);


> 0 32(1)
>0 32 (1)


> 0 32(2)
>0 32 (2)


>为什么在(1)和(2)中打印0?
>Why 0 is printed in (1) and (2) ??



你很幸运,它打印出一些你认识的东西

立即为奇数。如果你不那么幸运,它可能会打印出你期待的东西,然后你可能已经尝试过

来在真实程序中使用这个操作来发现很多太晚了

你的代码是不正确的。


用一个更直接的形式来表达上述内容:*任何*答案本来是

正确,因为左移或右移的结果为负值

值在C中未定义(因为移位超过

的比特数)提升的价值。)


-

如果你撒谎到编译器,它将报复。 - Henry Spencer

You got lucky and it printed out something that you recognize
immediately as being odd. If you had been less lucky, it might have
printed something you were expecting, and you might have then tried
to use the operation in a real program only to discover much too late
that your code was incorrect.

To phrase the above in a blunter form: *any* answer would have been
right, because the result of left or right shifting by a negative
value is undefined in C (as is the result of shifting by more than
the number of bits in the promoted value.)

--
If you lie to the compiler, it will get its revenge. -- Henry Spencer


这篇关于关于&lt;&lt;和&gt;&gt;运营商的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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