This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
public class main {
public static void main(String[] args) {
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
System.out.printf("%d %d\n",x,y);
}
//Output : 56,93
#include<stdio.h>
void main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d ",x,y);
}
//Output : 57 94
According to Operator Precedence Rules whatever output I got through Java code is right but when executing the same in 'C' code it incremented the output values by 1. I am using ubuntu 12.04 64-bit Operating System.
It's not the same thing because Java and C are different languages.
The behaviour of post increment in Java is defined as performing the increment after the expression has been evaluated.
The behaviour in C is undefined but often follows the order of precedence.
Note: order of evaluation and precedence are different things and this is more obvious for post increment/decrement and short cut boolean operations.
e.g.
Sting s = null;
if (s == null || !(s.length() > 0))
In this case ! has the highest precedence, but in reality will never be evaluated because the lower precedence || prevents it.
Precedence only determines where the implied brackets are, but only suggest how the expression might be evaluated.
Related
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 months ago.
I found that the precedence and associativity rules are different in C, C++ and Java.
Have a look at this code snippet:
#include<stdio.h>
void main(){
int k = 5;
int x = ++k*k--*4;
printf("%d",x);
}
The above C program gives the output as 120
Look the following Java code:
class Main
{
public static void main(String args[])
{
int k = 5;
int x = ++k*k--*4;
System.out.println(x);
}
}
This Java code gives 144 as output.
Why this difference?
I think the Java evaluation strategy is correct because it is evaluated as (pre increment)6 * 6 (post decrement) *4 = 144
Then what's wrong with C and C++? C and C++ both give 120.
In Java, left to right evaluation of most operands, including side effects, is guaranteed.
C and C++ make no such guarantee. Except for ||, &&, ?: (the ternary operator) and , (the comma operator), the evaluation order of operands is unspecified, as is any side effects that may result.
In this case:
int x = ++k*k--*4;
The variable k is written to more than once without an intervening sequence point. This triggers undefined behavior.
I was going through some exercises but I am confused in this one:
public static int f (int x, int y) {
int b=y--;
while (b>0) {
if (x%2!=0) {
--x;
y=y-2;
}
else {
x=x/2;
b=b-x-1;
}
}
return x+y;
}
What is the purpose of b=y--?
So, for example, x=5 and y=5
when we first go inside of while loop (while (b>0)) will b = 4 or 5? When I am running the code in my computer b is 5. And the return is 3. It is really unclear to me. Sorry if I am unclear in my question.
int b=y--; first assignes b=y and then decrements y (y--).
Also take a look at the prefix/postfix unary increment operator.
This example (taken from the linked page) demonstrates it:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
The difference between a post-increment/decrement and a pre-increment/decrement is in the evaluation of the expression.
The pre-increment and pre-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. In contrast, the post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation.
In other words:
int a = 5;
int b;
b = --a; // the value of the expression --a is a-1. b is now 4, as is a.
b = a--; // the value of the expression a-- is a. b is still 4, but a is 3.
Remember that a program must evaluate expressions to do everything. Everything is an expression, even just a casual mention of a variable. All of the following are expressions:
a
a-1
--a && ++a
System.out.println(a)
Of course, in the evaluation of expressions, operator precedence dictates the value of an expression just as the PEMDAS you learned in grade school. Some operators, such as increment/decrement, have side effects, which is of course great fun, and one of the reasons why functional programming was created.
I believe b would equal 5 entering the loop because
b=y--;
When the "--" is behind the variable it decrements it after the action.
It's poor coding, as it can confuse new programmers.
The function, assuming it is passing by value, like in the example above (as opposed to passing by reference) takes a copy of y, decrements it, and assigns it to b. It does not alter the argument passed to the function when it was called.
Post increment
x++;
x += 1;
Post decrement
x--;
x -=1;
Pre increment : ++x;
Pre decrement : --x;
According to the Head First Java:
Difference between x++ and ++x :
int x = 0; int z = ++x;
Produces: x is 1, x is 1
in x = 0; int z = x++;
Produces: x is 1, z is 0
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to understand how can the int x be incremented inside an if (Boolean expression) for every loop iteration
How is that possible?? How does it work?
public class MethodsTest {
public static void main(String[] args) {
int x= 0;
for (int z = 0; z < 5; z++)
{
if(x++ > 2){
}
System.out.println(x);
}
}
}
the output will be
1
2
3
4
5
x++ is a compound assignment operator, which is equivalent to x = x + 1, with the side effect taking place after the evaluation. Therefore, the if statement is equivalent to a pair of statements like this:
if(x > 2) {
x = x + 1;
// At this point, the side effect has taken place, so x is greater than it was before the "if"
...
} else {
// The side effect takes place regardless of the condition, hence the "else"
x = x + 1;
}
Note that this code is forced to repeat the x = x + 1 part. Using ++ lets you avoid this repetition.
There is a pre-increment counterpart of x++ - namely, ++x. In this form the assignment takes place before the expression is evaluated, so the condition becomes
if ((x = x + 1) > 2) {
// Note that the condition above uses an assignment. An assignment is also an expression, with the result equal to
// the value assigned to the variable. Like all expressions, it can participate in a condition.
}
To break your notion that the condition of an if can't "do things", imagine that you have a function that returns a boolean, like:
boolean areThereCookies(int numCookies)
{
return numCookies > 0;
}
then you could use it in your if statement:
if (areThereCookies(cookies))
{
eatCookies(cookies);
}
However the method areThereCookies(int) that we are calling to evaluate the if condition could be making anything in the world. It could change variable values, read input, write output, steal cookies...
So the language is perfectly capable of "doing things" in the if evaluation. The other answers explain what your code was specifically doing.
Cheers.
You are allowed to have expressions inside a if statement as long as the expression resolves to a boolean. For example,
int i = 0
if (i = i + 1)
is not a valid expression inside an if statement because the expressions resolves to 1, which is an integer.
However,
int i = 0
if (2 == i = 2)
is a valid expression because 2 is first assigned to the variable i and then is compared to 2, and thus the expression resolves to “true”.
In your example if statement, you have a post-incremented variable x that is compared against 2 with the greater than operator, resulting in a boolean value, and thus it is a valid expression. Hotlinks has described what a post-incremented variable is in the comments.
This question already has answers here:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)? [duplicate]
(6 answers)
Closed 9 years ago.
[I thought this would have been asked already, but I can't find an answer].
When writing an if statement, should the thing I'm comparing against come first or second? (I am specifically curious about both C / C++ and Java).
Does it matter, or is it just stylistic? (Convention seems to be "variable first, value second").
Consider the following code:
#include <iostream>
int main() {
int x = 5;
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
if ( x == 5 ) {
std::cout << "5 == X, true." << std::endl;
}
return 0;
}
which outputs:
X == 5, true.
5 == X, true.
so there doesn't appear to be any difference. Are there subtleties I'm missing?
These are called Yoda Conditions and to my knowledge the main idea is to guard against accidental assignment (i.e. you can't assign to literals).
Yes, worth mentioning that something like if (a = 5) where a is not a bool is not allowed in languages such as Java (though OK in C/C++), but as the Wikipedia article points out it is still possible to guard against unwanted behavior:
It can also solve some types of unsafe null behavior.
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
With Yoda Conditions:
String myString = null;
if ("foobar".equals(myString)) { /* ... */ }
// This is false, as expected
Putting the constant first (aka "Yoda style") prevents problems from a simple typo:
if (x = 5) // if (x == 5) was intended
...still compiles but does the wrong thing (though most current compilers will warn about the problem).
if (5 = x) // if (5 == x) was intended
...absolutely cannot compile on anything even approaching a properly functioning compiler.
No, there is no difference. It doesn't matter. Do whatever you like. Personally I'd do:
x == 5
Because it reads better (or so I think). 5 == x just doesn't sound right. But again, personal opinion.
I think you'll find that most people do x == 5 because you are comparing x, rather than comparing 5.
Both are ok.
But it is more accepted to do so when the parameter on left side.
example:
if ( x == 5 )
Anyway. it doesn't matter, do whatever you pleased and feel more comfortable with.
In most cases you'll find the common practice is to have the variable come first because the operator == means assignment and here you are assigning the value 5 so it only makes sense to have the variable come first.
Your if statement should then look like this:
if ( 5 == x ) {
std::cout << "X == 5, true." << std::endl;
}
I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");