表达式 "j = ++(i | i);和 j = ++(i & i);应该是左值错误? [英] Expressions "j = ++(i | i); and j = ++(i & i); should be a lvalue error?

查看:39
本文介绍了表达式 "j = ++(i | i);和 j = ++(i & i);应该是左值错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待在我的以下代码中:

I was expecting that in my following code:

#include<stdio.h> 
int main(){
    int i = 10; 
    int j = 10;

    j = ++(i | i);
    printf("%d %d
", j, i);

    j = ++(i & i);
    printf("%d %d
", j, i);

    return 1;
}

表达式 j = ++(i | i);j = ++(i & i); 将产生如下左值错误:

expressions j = ++(i | i); and j = ++(i & i); will produce lvalue errors as below:

x.c: In function ‘main’:
x.c:6: error: lvalue required as increment operand
x.c:9: error: lvalue required as increment operand   

但令我惊讶的是,上面的代码编译成功,如下:

But I surprised that above code compiled successfully, as below:

~$ gcc x.c -Wall
~$ ./a.out 
11 11
12 12   

检查上述代码是否正常工作.

而其他运算符会产生错误(据我所知).即使按位运算符 XOR 导致错误 j = ++(i ^ i); (检查其他 operators在编译时产生左值错误).

While other operators produce error (as I understand). Even bitwise operator XOR causes of an error j = ++(i ^ i); (check other operators produce an lvalue error at compilation time).

是什么原因?这是未指定还是未定义?还是按位 OR AND 运算符不同?

What is the reason? Is this is unspecified or undefined ? or bitwise OR AND operators are different?

编译器版本:

gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu5)

但我相信编译器版本不应该导致不统一的行为.如果 ^ 未编译,则 |& 也未编译.否则应该适用于所有人

But I believe compiler version shouldn't reason for non-uniform behavior. If ^ not compiled then | and & also not. otherwise should work for all

这个编译器在 c99 模式下不是错误:gcc x.c -Wall -std=c99.

Its not an error with this compiler in c99 mode: gcc x.c -Wall -std=c99.

推荐答案

你说得对,它不应该编译,而且在大多数编译器上,它不编译.
(请具体说明哪个编译器/版本没有给你一个编译器错误)

You are right that it should not compile, and on most compilers, it does not compile.
(Please specify exactly which compiler/version is NOT giving you a compiler error)

我只能假设编译器知道 (i | i) == i(i & i) == i 的身份并且正在使用它们身份来优化表达式,只留下变量 i.

I can only hypothesize that the compiler knows the identities that (i | i) == i and (i & i) == i and is using those identities to optimize away the expression, just leaving behind the variable i.

这只是一个猜测,但对我来说很有意义.

This is just a guess, but it makes a lot of sense to me.

这篇关于表达式 &quot;j = ++(i | i);和 j = ++(i &amp; i);应该是左值错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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