home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / lang / c / 18656 < prev    next >
Encoding:
Text File  |  1992-12-21  |  2.2 KB  |  79 lines

  1. Newsgroups: comp.lang.c
  2. Path: sparky!uunet!spool.mu.edu!umn.edu!mmm.serc.3m.com!pwcs!cdsmn!wells
  3. From: wells@cdsmn.mn.org (Rich Wells)
  4. Subject: a ? b : c = d; /* legal ? */
  5. Message-ID: <BzDA4u.459@cdsmn.mn.org>
  6. Summary: interpretation question re conditional operator
  7. Keywords: interpretation, conditional operator, language issue
  8. Organization: Dicomed, Inc
  9. X-Newsreader: TIN [version 1.1 PL6]
  10. Date: Wed, 16 Dec 1992 19:29:17 GMT
  11. Lines: 66
  12.  
  13. Is the statement:
  14.  
  15.     a ? b : c = d;
  16.  
  17. where a, b, c, and d are all integers, a valid C expression?
  18. I suspect not, since precedence rules determine that the
  19. statement is equivalent to
  20.  
  21.     (a ? b : c) = d;
  22.  
  23. and since the ?: operator does not yield an lvalue, the
  24. expression is flawed.
  25.  
  26. The above argument is based on the book _ANSI C: A Lexical
  27. Guide_, a not entirely unimpeachable source, so I thought
  28. I'd consult the net.wisdom for the correct answer.
  29.  
  30. Also, the three compilers I have experimented with each have
  31. different interpretations.  To wit:
  32.  
  33. ***** Microsoft C (7.0 and 5.1):
  34.  
  35. The statement does not compile.  The compiler complains
  36. (rightly, I think) that the ?: does not yield an lvalue,
  37. and so the assignment is invalid.
  38.  
  39. ***** Metaware HighC (version 3.01 for the 386):
  40.  
  41. The statement is interpreted as:
  42.  
  43.     if (a)
  44.         b;
  45.     else
  46.         c = d;
  47.  
  48. which, it seems to me, ignores precedence rules.
  49.  
  50. ***** Turbo C++ (3.0):
  51.  
  52. The statement is interpretted as:
  53.  
  54.     if (a)
  55.         a = d;
  56.     else
  57.         b = d;
  58.  
  59. In other words, it allows the ?: operator to yield an
  60. lvalue, and uses that for the assignment.  (NOTE: TC++
  61. is a C++ compiler; does this change the answer?)
  62.  
  63. *****
  64.  
  65. So that I don't have to go out and buy an asbestos suit, I
  66. want to make it very clear that I would never even consider
  67. writing code like this.  This came from a friend of a friend
  68. (perhaps I should post to alt.folklore.computers?) who claims
  69. he was asked this on an employment exam, and was told that
  70. the Turbo C++ interpretation is correct.
  71.  
  72. BTW: if I have used the words 'statement', 'expression' and
  73. 'lvalue' wrong, forgive me; I'm not an experienced language
  74. lawyer.  However, please correct me if I used them wrong;
  75. inquiring minds want to know.
  76. -- 
  77.  
  78. Richard Wells  wells@cdsmn.mn.org  or  ...!tcnet!cdsmn!wells
  79.