Bifalgorithm post · Computer science one · Computing a Logarithm

Why does an extra semicolon make the conditional statement ineffective?

Why does an extra semicolon make the conditional statement ineffective? (Computer science one · Computing a Logarithm) — "This PHP code will run without error…

Ideas in this flowchart

  • La instrucción printf se ejecuta aunque x sea 15 porque el punto y coma deja vacío el cuerpo condicional.
  • Una instrucción condicional se vincula con la instrucción ejecutable o el bloque de código que aparece inmediatamente después.
  • El punto y coma proporciona una instrucción ejecutable vacía.
  • El código equivale a una condición con un bloque vacío seguida de una llamada a printf.
  • El bloque if no contiene ninguna acción ejecutable.
  • La llamada a printf aparece después del bloque condicional y no está vinculada al if.
  • Por eso se imprime «x is less than 10» aunque x = 15.
  • El código se ejecuta sin errores ni advertencias.
  • Este comportamiento no es el resultado que se pretendía.
Feed/

Why does an extra semicolon make the conditional statement ineffective?

No cover

Channel

Computer science one

1 page

"This PHP code will run without error or warning. However, it will end up printing x is less than 10, even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this case, we’ve provided an empty executable statement ended by the semicolon. The code is essentially equivalent to:\n\n$x = 15;\n\nif($x < 10) {\n\n}\n\nprintf(\"x is less than 10\n\n\");\n\nThis is obviously not what we wanted. The semicolon was bound to the empty executable statement and the code block containing the print statement immediately followed, but was not bound to the conditional statement which is why the print statement executed regardless of the value of x."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.