为什么增量运算符不起作用? [英] Why increment operator doesn't work?

查看:159
本文介绍了为什么增量运算符不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

未定义的行为和序列点






  int a = 10; 

a = a ++;


a = ++ a;


a =(a ++);






你们可以向我解释为什么这些情况下工作?

解决方案

在回答这个代码的C ++问题在 http://codepad.org/cYXEuRuQ

 #include< iostream.h> 
int main()
{
int a = 10;
a = a ++;
cout<< a;
cout<<\\\
;
a = ++ a;
cout<< a;
cout< <\\\
;
a =(a ++);
cout<< a;
cout<<\\\
;
}

  cc1plus:警告被视为错误
在函数'int main()':
行5:警告:对'a'的操作可能未定义
行8:警告:对'a'的操作可能未定义
行11:警告:对'a'的操作可能未定义

这是一个警告,指出所使用的操作未定义,如果可能,不应使用。这是因为在C ++中, ++ 相对于其他表达式的求值顺序没有定义,并且在所有编译器中不一样。 (一般来说这没关系,除了像这样的边缘情况下不是问题)



网站进一步处理警告并且不运行代码






如果您翻译为Java,则会输出

  10 
11
11

。 不工作是什么意思?



这个行为是在Java中定义的,但是LucTouraille指出它在C ++中没有定义,所以你不能期望

 <$ c 

$ c> int a = 3;
a = a ++ * a ++;
System.out.println(a); //在Java中总是为12。

它与

相同

  {
int t1 = a;
a = a + 1;
int t2 = a;
a = a + 1;
a = t1 * t2;
}


Possible Duplicate:
Undefined Behavior and Sequence Points

int a=10;

a=a++;


a=++a;


a=(a++);


Can you guys please explain to me why none of these cases works?

解决方案

In answer to the C++ question for this code at http://codepad.org/cYXEuRuQ

#include<iostream.h>
int main()
{
int a=10;
a=a++;
cout<<a;
cout<<"\n";
a=++a;
cout<<a;
cout<<"\n";
a=(a++);
cout<<a;
cout<<"\n";
}

when compiled prints

cc1plus: warnings being treated as errors
In function 'int main()':
Line 5: warning: operation on 'a' may be undefined
Line 8: warning: operation on 'a' may be undefined
Line 11: warning: operation on 'a' may be undefined

This is a warning stating that the operation used is undefined and should not be used if possible. This is because in C++ the order of evaluation of ++ relative to other expressions is not defined and not the same across all compilers. (Generally it doesn't matter and is not a problem except in edge cases like these)

The web site goes further and treats warnings as errors and does not run the code.


If you translate to Java it prints

10
11
11

as expected. What do you mean by "doesn't work"?

The behaviour is defined in Java, but as LucTouraille points out its not defined in C++ so you can't expect a particular behaviour which is the same for all compilers.

Another example.

int a = 3;
a = a++ * a++;
System.out.println(a); // will always be 12 in Java.

it is the same as

{
    int t1 = a;
    a = a + 1;
    int t2 = a;
    a = a + 1;
    a = t1 * t2;
}

这篇关于为什么增量运算符不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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