Home > Backend Development > C++ > body text

When and How to Use Extra Parentheses in C to Manipulate Name Lookup, Comma Operator Behavior, or Expression Evaluation?

Mary-Kate Olsen
Release: 2024-10-24 03:37:30
Original
394 people have browsed it

When and How to Use Extra Parentheses in C   to Manipulate Name Lookup, Comma Operator Behavior, or Expression Evaluation?

Extra Parentheses in C : Beyond Operator Precedence

Although extra parentheses generally don't alter the meaning of a C program, there are specific situations where they do have an effect, beyond overriding basic operator precedence:

1. Preventing Argument-Dependent Name Lookup

Parentheses around function calls, such as (fn)(arg), prevent argument-dependent name lookup (ADL). Without parentheses, fn(arg) would search in enclosing namespaces for possible matching functions.

2. Enabling Comma Operator in List Contexts

In list contexts like function arguments or initializer lists, a, (b, c), d allows the comma operator to apply to (b, c) separately, unlike the standard a, b, c, d notation.

3. Ambiguity Resolution in Vexing Parses

Extra parentheses can disambiguate code where a declaration-like syntax clashes with a function or expression statement. For example, in S w(int(a)); and S y((int)a);, parentheses make it clear they are object declarations, not function declarations.

4. Deducing Referenceness in decltype Expressions

decltype(e) deduces whether the operand is an lvalue or rvalue reference. Adding parentheses, as in decltype((e)), forces the operand to be treated as an rvalue reference.

5. Preventing Preprocessor Macro Errors

Parentheses can be used within macro definitions to avoid operator precedence issues, protect macro arguments with commas, and prevent macro expansion in headers. For example, #define TIMES(A, B) (A) * (B); ensures that TIMES(1 2, 2 1) evaluates to 9.

The above is the detailed content of When and How to Use Extra Parentheses in C to Manipulate Name Lookup, Comma Operator Behavior, or Expression Evaluation?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!