0

From my understanding you need opening and closing braces for any 'standard construct in the language' (eg. a for loop/if statement etc. I don't know the real word for it) that contains multiple statements. So, why is this K&R C valid...

while((len = getline(line, MAXLINE)) > 0)
  if(len > max) {
    max = len;
    copy(longest, line);
  }

There's no braces on the while loop however, it does contain multiple statements (when the if is true). This is from example 1.9 in the 2nd edition of K&R's The C Programming Language.

CS Student
  • 1,613
  • 6
  • 24
  • 40
  • 1
    the while loop only contains one statement: an `if` statement. – Michael Edenfield Dec 21 '13 at 14:22
  • The `if`-block counts as one statement... Wait, where's the actual question? – Kninnug Dec 21 '13 at 14:22
  • The same can be done for `if` or `for` or `do ... while` as well. Anywhere you can have a block statement, if there's only one statement then the braces can be omitted (except function bodies). And while it's originated with old K&R C, it's in the modern standard as well. – Some programmer dude Dec 21 '13 at 14:25
  • Answers to this really needs to be quoting the standard IMO... – Bernhard Barker Dec 21 '13 at 14:25
  • 1
    The while loop is `while (condition) statement`. The `if (condition) { statements }` is a statement. The extra braces are desirable (I'd put them there) but not necessary. – Jonathan Leffler Dec 21 '13 at 14:25
  • @MichaelEdenfield Right, its really that simple. Thanks :). Just out of interest, is the omition of braces just there so the programmer can type slightly less/have "cleaner" looking code? Personally I think its quite a bad feature of the language... – CS Student Dec 21 '13 at 14:27
  • @CSStudent it's also the beginning of a scope... so it actually does something... see: http://stackoverflow.com/questions/2759371/in-c-do-braces-act-as-a-stack-frame – Homer6 Dec 21 '13 at 14:35

2 Answers2

4

Because the if is read as a single statement body for the while. It's perfectly valid.

Homer6
  • 15,034
  • 11
  • 61
  • 81
bugmagnet
  • 7,631
  • 8
  • 69
  • 131
4

In your case, there's only one statement under your while loop which is the if condition. In that case, this code is correct.

Gabriel L.
  • 4,678
  • 5
  • 25
  • 34