What is the advantage of commas in a conditional statement?

后端 未结 7 1721
醉酒成梦
醉酒成梦 2021-02-03 17:25

We can write an if statement as

if (a == 5, b == 6, ... , thisMustBeTrue)

and only the last condition should be satisfiable to ent

相关标签:
7条回答
  • 2021-02-03 17:49

    My question is what is the advantage of commas in if or while statement? Why is it allowed ?

    It exists because statements and expressions are different things in C. A compound expression is a construct that is understood from theory (and some other languages) and would be missing without having added it in the form of the comma. Its use in the for statement was the original justification of why they needed it.

    But, by making the language more complete from a sound theoretical point of view, it later finds uses that nobody planned. The early C++ was a translator that generated C as its output, and having a sequential expression was absolutely essential in allowing inline functions to really generate "in line" logic in the C code.

    That includes any place the expression appears, including the condition of an if statement.

    Similarly, it has been used in "interesting" macros. And as much as C++ did away with macros by providing inline functions, as late as up-to-x11 compilers found the Boost FOREACH range loop (eventually, an emulation of the feature added to the language in x11) very handy, and that was a devilishly clever set of macros that involved the comma operator.

    (Hmm, the current version expands into multiple statements using chained if/else, rather than cramming it all into a single while.)

    Now, there is another way to put any statement into an expression (lambdas), so future crazy business of macros that emulate even newer language features or domain-specific embedded languages might not need to use that anymore.


    So, don't write code like that. Unless it's clear and indeed simpler than writing helper functions or splitting into multiple statements.

    But it may be just the thing for a macro that you want to easily use in one place and that place is inside the parens of an if or while. That could be justified in a domain-specific language hosted inside the C++ source code, or a language emulation feature like (perhaps) an alternative to exception handling used in an embedded real-time system.

    In short, it doesn't have a normal good usage. But it's there for completeness and you never know when someone will find it useful.

    0 讨论(0)
提交回复
热议问题