In many languages, such as Java and C/C++, comparisons are always done of the form <=
and >=
. For example, here is a working sample program:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 >= input2) {
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
And this compiles and runs correctly. However, if I change the one comparison line to be:
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Get inputs
int input1 = s.nextInt();
int input2 = s.nextInt();
// compare them
if (input1 => input2) { // ------Changed this line------
System.out.println("Input 1 is greater than or equal to input 2");
} else {
System.out.println("Input 1 is less than input 2");
}
}
}
It produces a compiler error here, as it does in many other languages.
This is most certainly an error generated from the language's grammar. But why would the grammar forbid such a comparison? From a programmer's perspective, it should not matter on which side of the equal sign the comparison operator is used.
Because both of the comparisons that have the operator on the left side of the equals, it makes sense that the syntax parsing is done linearly (either left-to-right, or vice versa). But why would the order matter?
Aucun commentaire:
Enregistrer un commentaire