-2

I just started learning C Programming and I have a question based on expression evaluation. If we have 3 variables, a,b, and c:

  1. c=a+++b++;
  2. c=a+++++b;

Why is the 1st expression valid and 2nd invalid?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Mohammed Shoaib
  • 344
  • 4
  • 11
  • The answer is colloquially known as the 'maximal munch' rule. The lexical analyzer will grab as much as it can to make a token. When it sees `c = a+++b++;`, it recognizes `a++ + b++`. When it sees `c = a+++++b;`, it recognizes `a++ ++ +b` and you can't increment the result of an increment operation. There must be other questions asking the same. – Jonathan Leffler Feb 28 '17 at 01:30
  • Adding to what Jonathan stated, that is the reason the compiler shall prompt you with *lvalue required for increment operator.* – Naman Feb 28 '17 at 01:32
  • @JonathanLeffler This may be a better duplicate (you beat me by 36 seconds): http://stackoverflow.com/questions/5341202/why-doesnt-ab-work-in-c – Jonathon Reinhart Feb 28 '17 at 01:32
  • 1
    @JonathonReinhart: hmmm — that's a good one for the second half; what I gave is a good one for the first half. Either could be acceptable; list both is good. The one disadvantage of Mjölnir is that it doesn't allow you to accumulate alternative duplicates unless someone has already nominated something else. – Jonathan Leffler Feb 28 '17 at 01:34
  • A better question is: why would anyone ever write something like `c=a+++++b;`. If you are a beginner, don't ponder about writing wildly obscure code. It is counter-productive and will make you worse at programming, not better. – Lundin Feb 28 '17 at 07:45
  • That being said, simply fix the expression by adding some minus symbols: `c = a+++-+-++b;`. Now spend some hours pondering why that one will compile, please. – Lundin Feb 28 '17 at 07:51
  • @JonathonReinhart: Added your suggestion using the new [Gold badge holders and moderators can now edit duplicate links](http://meta.stackexchange.com/questions/291824/gold-badge-holders-and-moderators-can-now-edit-duplicate-links) feature. It seems to work! – Jonathan Leffler Mar 03 '17 at 23:19
  • @JonathanLeffler Awesome! That's a very nice feature to finally have. – Jonathon Reinhart Mar 03 '17 at 23:29

1 Answers1

-1

It appears that the C compiler does interpret a+++ as a++ +, while +++b generates an error even if you put another variable before it.

In practice it is a very bad idea to write such expressions without spaces. You would confuse yourself when you come back to look at your code, and annoy anyone else looking at it :) Just rewrite:

  1. a++ + b++
  2. a++ + ++b

and everything will work as expected.

Demq
  • 21
  • 2