Bifalgorithm post · Computer science one · If, If-Else, If-Else-If Statements

What happens when a semicolon is placed after an if condition in C?

What happens when a semicolon is placed after an if condition in C? (Computer science one · If, If-Else, If-Else-If Statements) — "Suppose we made a mistake an…

Ideas in this flowchart

  • Unintended semicolon after an if condition changes the behavior of valid C code.
  • The conditional is written as if(x < 10);
  • The code is valid C and will compile and run, although some compilers may warn.
  • An if statement binds to the executable statement or code block immediately following it.
  • The semicolon supplies an empty executable statement for the if statement.
  • The following printf block is separate from the if statement.
  • Because x equals 15, the condition x < 10 is false.
  • The separate block nevertheless prints "x is less than 10".
  • The code is effectively equivalent to an if statement containing an empty block followed by the printing block.
Feed/

What happens when a semicolon is placed after an if condition in C?

No cover

Channel

Computer science one

1 page

"Suppose we made a mistake and did include a semicolon:\n\nint x = 15;\n\nif(x < 10); {\n\nprintf(\"x is less than 10\n\n\");\n\n}\n\nSome compilers may give a warning, but this is valid C; it will compile and it will run. 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\nint x = 15;\n\nif(x < 10) {\n\n}"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.