Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a level of precedence for operators such as static_cast?

According to cppreference.com, the C++ static_cast operator's level of precedence is 2.

Why are those levels even defined? I can't think of any reason. Can anyone provide an example?

like image 642
qdii Avatar asked Jan 11 '12 14:01

qdii


People also ask

Why is meant by precedence of operators?

The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator. Parentheses may be used to force precedence, if necessary.

What is the use of static_cast in C++?

The static_cast operator converts variable j to type float . This allows the compiler to generate a division with an answer of type float . All static_cast operators resolve at compile time and do not remove any const or volatile modifiers.

What is the importance of precedence and associativity write the table for operator precedence?

Operator precedence determines which operation is performed first in an expression with more than one operators with different precedence. Operators Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left.

What is the importance of precedence and associativity?

Precedence is the priority for grouping different types of operators with their operands. Associativity is the left-to-right or right-to-left order for grouping operands to operators that have the same precedence.


2 Answers

The standard doesn't define precedence levels; these can be derived from the grammar.

Like any other syntactical feature, static_cast has a place in this grammar. Because its use requires parentheses its operand expression can never be ambiguous, but that only means that it makes no sense to bother deriving a precedence level for it from the grammar, not that its place in the grammar itself is meaningless. Thus the standard is doing nothing crazy here.

What's pointless is that whatever source you cited listed a precedence level for static_cast. It's not wrong, it's just pointless.

like image 188
Lightness Races in Orbit Avatar answered Nov 07 '22 22:11

Lightness Races in Orbit


The C++ cast operator’s level of precedence is 2

Who said this? The standard doesn't define operator precedence. It defines the grammar in a BNF-like notation.

like image 27
Yakov Galka Avatar answered Nov 07 '22 22:11

Yakov Galka