Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Operators in C and C++
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Binding=== The binding of operators in C and C++ is specified by a factored language grammar, rather than a precedence table. This creates some subtle conflicts. For example, in C, the syntax for a conditional expression is: <syntaxhighlight lang="c">logical-OR-expression ? expression : conditional-expression</syntaxhighlight> while in C++ it is: <syntaxhighlight lang="cpp">logical-OR-expression ? expression : assignment-expression</syntaxhighlight> Hence, the expression: <syntaxhighlight lang="text">e = a < d ? a++ : a = d</syntaxhighlight> is parsed differently in the two languages. In C, this expression is a syntax error, because the syntax for an assignment expression in C is: <syntaxhighlight lang="c">unary-expression '=' assignment-expression</syntaxhighlight> In C++, it is parsed as: <syntaxhighlight lang="cpp">e = (a < d ? a++ : (a = d))</syntaxhighlight> which is a valid expression.<ref>{{cite web |title=C Operator Precedence - cppreference.com |url=https://en.cppreference.com/w/c/language/operator_precedence |website=en.cppreference.com |access-date=10 April 2020}}</ref><ref>{{Cite web|url=https://stackoverflow.com/questions/13515434/does-the-c-c-ternary-operator-actually-have-the-same-precedence-as-assignment/13515505|title=Does the C/C++ ternary operator actually have the same precedence as assignment operators?|website=Stack Overflow|access-date=2019-09-22}}</ref> To use the comma operator in a function call argument expression, variable assignment, or a comma-separated list, use of parentheses is required.<ref>{{cite web |title=Other operators - cppreference.com |url=https://en.cppreference.com/w/c/language/operator_other |website=en.cppreference.com |access-date=10 April 2020}}</ref><ref>{{cite web |title=c++ - How does the Comma Operator work |url=https://stackoverflow.com/questions/54142/how-does-the-comma-operator-work/ |website=Stack Overflow |access-date=1 April 2020}}</ref> For example, <syntaxhighlight lang="cpp"> int a = 1, b = 2, weirdVariable = (++a, b), d = 4; </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)