program { int x = 10; int y = 5; bool activo = 1; int resultado = x + y * 2; // 20 // Relational operators with logical AND if (resultado > 15 && activo == 1) { x = x + 100; // Nested condition with relational operator if (x >= 110) { y = y * y; // 25 } else { y = 0; } } else { resultado = 999; }}
program { int a = 10; int b = 5; int c = 3; bool flag = 1; // Arithmetic operators int sum = a + b; // 15 int diff = a - b; // 5 int prod = a * b; // 50 int quot = a / b; // 2 // Relational operators if (a > b) { } // true if (a < b) { } // false if (a == 10) { } // true if (a != b) { } // true if (a >= 10) { } // true if (b <= 5) { } // true // Logical operators if (a > b && flag == 1) { } // true AND true = true if (a < b || flag == 1) { } // false OR true = true if (!(a < b)) { } // NOT false = true // Combined operators if ((a + b) * c > 40 && flag == 1) { // (10 + 5) * 3 > 40 && 1 == 1 // 45 > 40 && true // true && true = true }}
Even when not required by precedence, parentheses improve readability:
// Without parentheses (correct but less clear)if (x > 5 && y < 10 || z == 0) { }// With parentheses (clearer intent)if ((x > 5 && y < 10) || z == 0) { }
Avoid Complex Expressions
Break down complex expressions into simpler steps:
// Complex (harder to debug)int result = (x + y * 2 - z / 3) * 4 + 5;// Simpler (easier to understand and debug)int temp1 = y * 2;int temp2 = z / 3;int temp3 = x + temp1 - temp2;int result = temp3 * 4 + 5;
Remember Precedence Rules
Keep the precedence hierarchy in mind:
Parentheses first
*/ before +-
Arithmetic before relational
Relational before logical
&& before ||
Use Consistent Comparison Style
Choose one style for not-equal and stick to it:
// Choose either != or <>, not bothif (x != 0) { } // Preferred// orif (x <> 0) { } // Alternative