Home > Backend Development > C++ > Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C ?

Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C ?

Barbara Streisand
Release: 2024-12-13 21:17:12
Original
431 people have browsed it

Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C  ?

Initializer Lists and the Right-Hand Side of Operators

Consider the following code snippet:

class foo { };

struct bar
{
    template<typename... T>
    bar(T const&amp;...) { }
};

foo&amp; operator<<(foo&amp; f, bar const&amp;) { return f; }

int main()
{
    foo baz;
    baz << {1, -2, "foo", 4, 5};

    return 0;
}
Copy after login

Compilers complain about the use of an initializer list on the right-hand side (RHS) of the operator <<. This raises questions about why this is disallowed in C , as opposed to cases where initializer lists are used in function arguments.

Initializer Lists and Expressions

Initializer lists are not expressions as defined in the C Standard. Arguments of functions and operators must generally be expressions. However, the Standard defines exceptions for initializer lists in certain contexts, including as function arguments, subscripts, and assignment expressions.

No Exception for Binary Operators

There is no exception for initializer lists to be used on the RHS (or left-hand side) of binary operators. This prohibition stems from parsing challenges that arise when allowing initializer lists as expressions. Using curly braces for both initializer lists and blocks would lead to ambiguity in the grammar.

Rationale for the Restriction

A proposal to extend the use of initializer lists to expressions was considered in 2007. However, it was determined that allowing initializer lists as right-hand operands of binary operators, but not as left-hand operands, would be too disruptive to the grammar.

Conclusion

Initializer lists cannot be used on the RHS of operators because they are not defined as expressions in the Standard. While certain exceptions exist for their use in specific contexts, allowing them as general operator arguments would pose significant parsing challenges due to the use of curly braces for both initializer lists and blocks.

The above is the detailed content of Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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