cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

Operator precedence

Operator overloading

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Common TypeScript Issues Nº 1: assignments within sub-expressions

Blog Author Phil Nash

Developer Advocate JS/TS

assignment operators shall not be used in sub expressions

We've been counting down our top 5 issues that SonarLint catches in TypeScript projects, and we've reached the top of the list. This issue is outstanding in its simplicity and potential to cause very hard-to-spot bugs.

Grab your editor and install SonarLint if you don't already have it. You can then copy and paste the example code below to try these for yourself. This particular issue applies to JavaScript codebases as well as TypeScript. 

.css-1s68n4h{position:absolute;top:-150px;} Nº 1: assignments within sub-expressions .css-5cm1aq{color:#000000;} .css-h4dt40{margin-left:10px;margin-top:-1px;display:inline-block;fill:#5F656D;margin-top:-2px;height:16px;width:16px;}.css-h4dt40:hover{fill:#290042;}

Have you ever written a conditional and then tested it out to find that it was not behaving how you'd expected it to? Whether or not the expression in the conditional is true or false, the code inside the conditional is still running. You go back to the code, checking every part of the expression and tracing the values back through the code. You verify everything is correct about it. You take one last look at it, ready to bang your head against the desk, close your laptop and go home for the day.

Finally, you spot it. The bug. There it is:

Inside the expression lies a single equals sign, the assignment operator. The sub-expression isn't checking whether the two variables are equal, it is assigning one to the other, and the conditional is being evaluated based on whether theOtherThing is a truthy value. 

The expression is missing an = (or perhaps two). It's a pain of a bug to figure out, it can take a long time to spot the last mistake you'd thought you'd make, and when you do find it, you kick yourself.

It's easy to spot in an isolated example like this but consider a more fully formed function:

It's not so obvious that the function above reassigns the method variable to the string GET and will always make a GET request regardless of the method supplied.

That's why assignment within sub-expressions is our number one issue discovered by SonarLint in TypeScript projects. Thankfully there aren't too many of these bugs in the wild, because they get caught by testing, linting, or by tooling like SonarLint. But between hunting for the bug or it being flagged in my editor as soon as I make the mistake, I know which I'd prefer.

Other causes .css-1jw8ybl{margin-left:10px;margin-top:-1px;display:inline-block;fill:#5F656D;margin-left:14px;}.css-1jw8ybl:hover{fill:#290042;}

Assigning inside a conditional is normally a bug, but there are other sub-expressions that assignments can crop up in. In these cases, the issue is less about correctness and more about readability.

Consider an example like this calculator class:

You can use it like so:

Each time you use the add or subtract methods the object returns the result, but also sets that result in an instance variable. In both functions, this is done in one line, conflating returning the value with storing it.

There is no bug here, the object works as expected, but this issue lies in the readability of the functions. It is unexpected to find an assignment in a return statement, and when you do you then need to read over the assignment in order to see the actual return value. This might be useful if you are trying to golf your code, but things are much more readable if you assign in one statement and then return the value in another.

While this is a relatively simple example, I have seen plenty of versions of this in real codebases where assigning and returning make reading the result much harder. In each of these cases, it is possible to make the assignment on one line and then return the result on the next line. It's more explicit and thus clearer to someone else reading the code.

Install SonarLint in your editor and you'll get notified if you accidentally assign inside of a conditional , avoiding those bugs, or if you're affecting readability by assigning within another expression .

That's a wrap

That's our countdown of the top 5 common issues we've found in TypeScript projects with SonarLint. Over this series we've covered:

5. Optional property declarations

4. Creating and dropping objects immediately

3. Unused local variables and functions

2. Non-empty statements

and, finally, today's issue

1. Assignments within sub-expressions 

I hope this has been an interesting trip through some of the issues you might have encountered in your own TypeScript, and hopefully cleared up before you commit. Check out the full set of TypeScript rules to see what other issues SonarLint can help you avoid. And if there are any rules you think should have made this top 5, let us know on Twitter at @SonarSource or in the community .

Help Center Help Center

  • Help Center
  • Trial Software
  • Product Updates

Documentation

  • Analysis Options
  • Polyspace Results

MISRA C :2004 and MISRA AC AGC Coding Rules

Supported misra c :2004 and misra ac agc rules.

The following tables list MISRA C™:2004 coding rules that the Polyspace ® coding rules checker supports. Details regarding how the software checks individual rules and any limitations on the scope of checking are described in the “Polyspace Specification” column.

The Polyspace coding rules checker:

Supports MISRA-C:2004 Technical Corrigendum 1 for rules 4.1, 5.1, 5.3, 6.1, 6.3, 7.1, 9.2, 10.5, 12.6, 13.5, and 15.0.

Checks rules specified by MISRA AC AGC Guidelines for the Application of MISRA-C:2004 in the Context of Automatic Code Generation .

The software reports most violations during the compile phase of an analysis. However, the software detects violations of rules 9.1 ( Non-initialized variable ), 12.11 (one of the overflow checks) using -scalar-overflows-checks signed-and-unsigned ), 13.7 (dead code), 14.1 (dead code), 16.2 and 21.1 during code analysis, and reports these violations as run-time errors.

Some violations of rules 13.7 and 14.1 are reported during the compile phase of analysis.

Troubleshooting

If you expect a rule violation but do not see it, check out Diagnose Why Coding Standard Violations Do Not Appear as Expected .

List of Supported Coding Rules

Environment, language extensions, character sets, identifiers, declarations and definitions, initialisation, arithmetic type conversion, pointer type conversion, expressions, control statement expressions, control flow, switch statements, pointers and arrays, structures and unions, preprocessing directives, standard libraries, runtime failures, unsupported misra c :2004 and misra ac agc rules.

The Polyspace coding rules checker does not check the following MISRA C:2004 coding rules. These rules cannot be enforced because they are outside the scope of Polyspace software. They may concern documentation, dynamic aspects, or functional aspects of MISRA rules. The Additional Information column describes the reason each rule is not checked.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

  • Switzerland (English)
  • Switzerland (Deutsch)
  • Switzerland (Français)
  • 中国 (English)

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

  • América Latina (Español)
  • Canada (English)
  • United States (English)
  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • United Kingdom (English)

Asia Pacific

  • Australia (English)
  • India (English)
  • New Zealand (English)

Contact your local office

Next: Write Assignments Separately , Previous: Postincrement/Postdecrement , Up: Assignment Expressions   [ Contents ][ Index ]

7.6 Pitfall: Assignment in Subexpressions

In C, the order of computing parts of an expression is not fixed. Aside from a few special cases, the operations can be computed in any order. If one part of the expression has an assignment to x and another part of the expression uses x , the result is unpredictable because that use might be computed before or after the assignment.

Here’s an example of ambiguous code:

If the second argument, x , is computed before the third argument, x = 4 , the second argument’s value will be 20. If they are computed in the other order, the second argument’s value will be 4.

Here’s one way to make that code unambiguous:

Here’s another way, with the other meaning:

This issue applies to all kinds of assignments, and to the increment and decrement operators, which are equivalent to assignments. See Order of Execution , for more information about this.

However, it can be useful to write assignments inside an if -condition or while -test along with logical operators. See Logicals and Assignments .

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

MISRA Discussion Forums

  • , Function type
  • MISRA-C++:2008 Standards Model Summary for C++

MISRA-C++:2008 Standards Model Summary for C++

Version 9.8.5 Copyright © 2020 LDRA Ltd. Copies of this document are not to be made or distributed.

MISRA- C ++:2008 Standards Model Summary for C++

The LDRA tool suite® is developed and certified to BS EN ISO 9001:2015, TÜV SÜD and SGS-TÜV Saar. This information is applicable to version 9.8.5 of the LDRA tool suite®. It is correct as of 22nd October 2020. © Copyright 2020 LDRA Ltd. All rights reserved.

Compliance is measured against "MISRA C++:2008 Guidelines for the use of the C++ language in critical systems" June 2008 Copyright © MISRA

Further information is available at http://www.misra.org.uk

Enhanced Fully Partially Not yet Not statically Classification Total Enforcement Implemented Implemented Implemented Checkable Required 11 170 12 4 1 198 Advisory 2 14 1 1 0 18 Document 0 2 2 0 8 12 Total 13 186 15 5 9 228

LDRA Ltd. reserves the right to change any specifications contained within this document without prior notice. The document was deemed correct at time of distribution. Version 9.8.5 Copyright © 2020 LDRA Ltd. Copies of this document are not to be made or distributed.

MISRA-C++:2008 Standards Model Compliance for C++ LDRA Rule Classification Rule Description LDRA Standard Description Standard 28 D Potentially infinite loop found. 76 D Procedure is not called or referenced in code analysed. 1 J Unreachable Code found. 0-1-1 Required A project shall not contain unreachable code. 3 J All internal linkage calls unreachable. 35 S Static procedure is not explicitly called in code analysed. 631 S Declaration not reachable. 139 S Construct leads to infeasible code. 0-1-2 Required A project shall not contain infeasible paths. 140 S Infeasible loop condition found. 94 D Named variable declared but not used in code. 0-1-3 Required A project shall not contain unused variables. 70 D DU anomaly, variable value is not used. 105 D DU anomaly dead code, var value is unused on all paths.

A project shall not contain non-volatile POD 0-1-4 Required 3 X Variable has only one use. variables having only one use.

A project shall not contain unused type 0-1-5 Required 413 S User type declared but not used in code analysed. declarations.

70 D DU anomaly, variable value is not used. A project shall not contain instances of non- 0-1-6 Required volatile variables being given values that are 105 D DU anomaly dead code, var value is unused on all paths. never subsequently used. 560 S Scope of variable could be reduced.

The value returned by a function having a non- 0-1-7 Required void return type that is not an overloaded 382 S (void) missing for discarded return value. operator shall always be used. All functions with void return type shall have 0-1-8 Required 65 D Void function has no side effects. external side effect(s).

70 D DU anomaly, variable value is not used.

105 D DU anomaly dead code, var value is unused on all paths. 0-1-9 Required There shall be no dead code.

57 S Statement with no side effect.

76 D Procedure is not called or referenced in code analysed. Every defined function shall be called at least 0-1-10 Required once. 2 U Procedure not called anywhere in system.

There shall be no unused parameters (named 1 D Unused procedure parameter. 0-1-11 Required or unnamed) in non-virtual functions. 15 D Unused procedural parameter. There shall be no unused parameters (named 1 D Unused procedure parameter. or unnamed) in the set of parameters for a 0-1-12 Required virtual function and all the functions that 15 D Unused procedural parameter. override it.

480 S String function params access same variable. An object shall not be assigned to an 0-2-1 Required overlapping object. 545 S Assignment of overlapping storage.

647 S Overlapping data items in memcpy. 0-3-1 Document Minimization of run-time failures shall be 43 D Divide by zero found. ensured by the use of at least one of: (a) static analysis tools/techniques; (b) dynamic 45 D Pointer not checked for null before use. analysis tools/techniques; (c) explicit coding of checks to handle run-time faults. 48 D Attempt to write to unopened file.

LDRA Ltd. reserves the right to change any specifications contained within this document without prior notice. The document was deemed correct at time of distribution. 0-3-1 Document Minimization of run-time failures shall be ensured by the use of at least one of: (a) static analysis tools/techniques; (b) dynamic analysis tools/techniques; (c) explicitVersion coding 9.8.5 Copyright © 2020 LDRA Ltd. of checks to handle run-timeCopies faults. of this document are not to be made or distributed.

49 D File pointer not closed on exit.

51 D Attempt to read from freed memory.

82 D fsetpos values not generated by fgetpos.

83 D Potentially repeated call to ungetc.

84 D No fseek or flush before I/O.

87 D Illegal shared object in signal handler.

89 D Illegal use of raise in signal handler.

98 D Attempt to write to file opened read only.

113 D File closed more than once.

123 D File pointer not checked for null before use.

124 D Var set by std lib func return not checked before use.

125 D free called on variable with no allocated space.

LDRA Ltd. reserves the right to change any specifications contained within this document without prior notice. The document was deemed correct at time of distribution. 0-3-1 Document Minimization of run-time failures shall be ensured by the use of at least one of: (a) static analysis tools/techniques; (b) dynamic analysis tools/techniques; (c) explicit coding of checks to handle run-time faults.

127 D Local or member denominator not checked before use.

128 D Global pointer not checked within this procedure.

129 D Global file pointer not checked within this procedure.

130 D Global set by std lib func return not checked before use.

131 D Global denominator not checked within this procedure.

135 D Pointer assigned to NULL may be dereferenced.

136 D Global pointer assigned to NULL may be dereferenced.

137 D Parameter used as denominator not checked before use.

64 S Void procedure used in expression.

65 S Void variable passed as parameter.

113 S Non standard character in source.

157 S Modification of string literal.

248 S Divide by zero in preprocessor directive.

407 S free used on string.

412 S Undefined behaviour, \ before E-O-F.

465 S Struct/union not completely specified.

482 S Incomplete structure referenced.

483 S Freed parameter is not heap item.

484 S Attempt to use already freed object.

486 S Incorrect number of formats in output function.

487 S Insufficient space allocated.

489 S Insufficient space for operation.

573 S Macro concatenation of uni char names.

576 S Function pointer is of wrong type.

587 S Const local variable not immediately initialised.

589 S Format is not appropriate type.

590 S Mode fault in fopen.

591 S Inappropriate use of file pointer.

608 S Use of explicitly undefined language feature.

629 S Divide by zero found.

642 S Function return type with array field.

644 S realloc ptr does not originate from allocation function.

645 S realloc ptr type does not match target type.

652 S Object created by malloc used before initialisation.

66 X Insufficient array space at call.

70 X Array has insufficient space.

71 X Insufficient space for copy.

79 X Size mismatch in memcpy/memset.

80 X Divide by zero found. 91 D Function return value potentially unused. If a function generates error information, then 105 D DU anomaly dead code, var value is unused on all paths. 0-3-2 Required that error information shall be tested. 124 D Var set by std lib func return not checked before use. 130 D Global set by std lib func return not checked before use. Use of scaled-integer or fixed-point arithmetic 0-4-1 Document shall be documented. Use of floating-point arithmetic shall be 0-4-2 Document documented. Floating-point implementations shall comply 0-4-3 Document with a defined floating-point standard. 145 S #if has invalid expression. 293 S Non ANSI/ISO construct used. 324 S Macro call has wrong number of parameters. 387 S Enum init not integer-constant-expression. All code shall conform to ISO/IEC 14882:2003 404 S Array initialisation has too many items. 1-0-1 Required "The C++ Standard Incorporating Technical 481 S Array with no bounds in struct. Corrigendum 1". 580 S Macro redefinition without using #undef. 582 S const object reassigned. 615 S Conditional operator has incompatible types. 646 S Struct initialisation has too many items.

Multiple compilers shall only be used if they 1-0-2 Document have a common, defined interface . The implementation of integer division in the 1-0-3 Document chosen compiler shall be determined and documented. The character set and the corresponding 2-2-1 Document encoding shall be documented. 2-3-1 Required Trigraphs shall not be used. 81 S Use of trigraph. 2-5-1 Advisory Digraphs should not be used. 295 S Use of digraph. The character sequence /* shall not be used 2-7-1 Required 119 S Nested comment found. within a C-style comment. Sections of code shall not be "commented out" 2-7-2 Required 302 S Comment possibly contains code. using C-style comments. Sections of code should not be "commented 2-7-3 Advisory 302 S Comment possibly contains code. out" using C++ comments. Different identifiers shall be typographically 217 S Names only differ by case. 2-10-1 Required unambiguous. 67 X Identifier is typographically ambiguous. 17 D Identifier not unique within *** characters. Identifiers declared in an inner scope shall not 2-10-2 Required 128 S Parameter has same name as global variable. hide an identifier declared in an outer scope. 131 S Name reused in inner scope. 61 X Identifier match in *** chars.

112 S Typedef name redeclared. 16 X Identifier reuse: typedef vs variable. 17 X Identifier reuse: typedef vs label (MR). 18 X Identifier reuse: typedef vs typedef. 19 X Identifier reuse: typedef vs procedure parameter. 20 X Identifier reuse: persistent var vs typedef. 21 X Identifier reuse: typedef vs macro. 22 X Identifier reuse: typedef vs component. 23 X Identifier reuse: typedef vs enum constant. A typedef name (including qualification, if any) 02/10/2003 Required shall be a unique identifier.

24 X Identifier reuse: typedef vs procedure.

552 S Class, enum, struct or union name reused (MR). 4 X Identifier reuse: struct/union tag repeated. 5 X Identifier reuse: struct vs union. 6 X Identifier reuse: struct/union tag vs enum tag. 7 X Identifier reuse: tag vs procedure. 8 X Identifier reuse: tag vs procedure parameter. A class, union or enum name (including 2-10-4 Required 9 X Identifier reuse: tag vs variable. qualification, if any) shall be a unique identifier. 10 X Identifier reuse: tag vs label (MR). 11 X Identifier reuse: tag vs typedef. 12 X Identifier reuse: tag vs macro. 13 X Identifier reuse: tag vs component. 14 X Identifier reuse: tag vs enum constant. 15 X Identifier reuse: persistent var vs tag.

7 X Identifier reuse: tag vs procedure. 15 X Identifier reuse: persistent var vs tag. 20 X Identifier reuse: persistent var vs typedef. 24 X Identifier reuse: typedef vs procedure. 25 X Identifier reuse: procedure vs procedure param. 26 X Identifier reuse: persistent var vs label (MR). 27 X Identifier reuse: persist var vs persist var. 28 X Identifier reuse: persistent var vs var. The identifier name of a non-member object or 29 X Identifier reuse: persistent var vs procedure. 2-10-5 Advisory function with static storage duration should not 30 X Identifier reuse: persistent var vs proc param. be reused. 32 X Identifier reuse: procedure vs var. 33 X Identifier reuse: procedure vs label (MR). 34 X Identifier reuse: proc vs macro. 35 X Identifier reuse: proc vs component. 36 X Identifier reuse: proc vs enum constant. 37 X Identifier reuse: persistent var vs macro. 38 X Identifier reuse: persistent var vs component. 39 X Identifier reuse: persistent var vs enum constant. If an identifier refers to a type, it shall not also 9 X Identifier reuse: tag vs variable. 2-10-6 Required refer to an object or a function in the same 11 X Identifier reuse: tag vs typedef. scope. 24 X Identifier reuse: typedef vs procedure. Only those escape sequences that are 2-13-1 Required 176 S Non standard escape sequence in source. defined in ISO/IEC14882:2003 shall be used. Octal constants (other than zero) and octal 83 S Octal number found. 2-13-2 Required escape sequences (other than "\0") shall not 376 S Use of octal escape sequence. A "U" suffix shall be applied to all octal or 2-13-3 Required 550 S Unsuffixed hex or octal is unsigned, add U. hexadecimal integer literals of unsigned type. 2-13-4 Required Literal suffixes shall be upper case. 252 S Lower case suffix to literal number. Narrow and wide string literals shall not be 2-13-5 Required 450 S Wide string and string concatenated. concatenated. It shall be possible to include any header file in 286 S Functions defined in header file. 3-1-1 Required multiple translation units without violating the 287 S Variable definition in header file. One Definition Rule. 3-1-2 Required Functions shall not be declared at block scope. 296 S Function declared at block scope. When an array is declared, its size shall either 3-1-3 Required be stated explicitly or defined implicitly by 127 S Array has no bounds specified. initialization.

36 D Prototype and definition name mismatch. 102 S Function and prototype return inconsistent (MR). All declarations of an object or function shall 3-2-1 Required 1 X Declaration types do not match across a system. have compatible types. 62 X Function prototype/defn return type mismatch (MR). 63 X Function prototype/defn param type mismatch (MR). 26 D Variable should be defined once in only one file. 34 D Procedure name re-used in different files. 3-2-2 Required The One Definition Rule shall not be violated. 4 X Identifier reuse: struct/union tag repeated. 18 X Identifier reuse: typedef vs typedef. 60 D External object should be declared only once. A type, object or function that is used in 110 D More than one prototype for same function. 3-2-3 Required multiple translation units shall be declared in 172 S Variable declared multiply. one and only one file. 354 S Extern declaration is not in header file. 26 D Variable should be defined once in only one file. An identifier with external linkage shall have 3-2-4 Required 33 D No real declaration for external variable. exactly one definition. 63 D No definition in system for prototyped procedure. 27 D Variable should be declared static. Objects or functions with external linkage shall 3-3-1 Required 61 D Procedure should be declared static. be declared in a header file. 354 S Extern declaration is not in header file. If a function has internal linkage then all re- 461 S Identifier with ambiguous linkage. 3-3-2 Required declarations shall include the static storage 553 S Function and proto should both be static. class specifier. 575 S Linkage differs from previous declaration. An identifier declared to be an object or type 25 D Scope of variable could be reduced. 3-4-1 Required shall be defined in a block that minimizes its 560 S Scope of variable could be reduced. visibility. 102 S Function and prototype return inconsistent (MR). The types used for an object, a function return 2 X Ambiguous declaration of variable. type, or a function parameter shall be token-for- 3-9-1 Required token identical in all declarations and re- 62 X Function prototype/defn return type mismatch (MR). declarations. 63 X Function prototype/defn param type mismatch (MR). typedefs that indicate size and signedness 90 S Basic type declaration used. 3-9-2 Advisory should be used in place of the basic 495 S Typedef name has no size indication. The underlying bit representations of floating- 345 S Bit operator with floating point operand. 3-9-3 Required point values shall not be used. 554 S Cast to an unrelated type. Expressions with type bool shall not be used 136 S Bit operator with boolean operand. as operands to built-in operators other than 249 S Operation not appropriate to boolean type. 4-5-1 Required the assignment operator =, the logical 389 S Bool value incremented/decremented. operators &&, ||, !, the equality operators == 506 S Use of boolean with relational operator.

Expressions with type enum shall not be used as operands to built-in operators other than the subscript operator [ ], the assignment 4-5-2 Required 123 S Use of underlying enum representation value. operator =, the equality operators == and !=, the unary & operator, and the relational operators , >=. Expressions with type (plain) char and wchar_t shall not be used as operands to built- 4-5-3 Required in operators other than the assignment 329 S Operation not appropriate to plain char. operator =, the equality operators == and !=, and the unary & operator. 4-10-1 Required NULL shall not be used as an integer value. 530 S NULL used in integer context. Literal zero (0) shall not be used as the null- 4-10-2 Required 531 S Literal zero used in pointer context. pointer-constant. 22 D Function has global variable side effects. 35 D Expression has side effects. The value of an expression shall be the same 72 D Potential side effect problem in expression. 5-0-1 Required under any order of evaluation that the 1 Q Call has execution order dependant side effects. standard permits. 9 S Assignment operation in expression. 30 S Deprecated usage of ++ or -- operators found. 134 S Volatile variable in complex expression. Limited dependence should be placed on C++ 49 S Logical conjunctions need brackets. 5-0-2 Advisory operator precedence rules in expressions. 361 S Expression needs brackets. A cvalue expression shall not be implicitly 451 S No cast for widening complex float expression (MR). 5-0-3 Required converted to a different underlying type. 452 S No cast for widening complex int expression (MR). 96 S Use of mixed mode arithmetic. 101 S Function return type inconsistent. 104 S Struct field initialisation incorrect. An implicit integral conversion shall not 107 S Type mismatch in ternary expression. 5-0-4 Required change the signedness of the underlying type. 109 S Array subscript is not integral. 331 S Literal value requires a U suffix. 434 S Signed/unsigned conversion without cast. 458 S Implicit conversion: actual to formal param (MR). 101 S Function return type inconsistent. 104 S Struct field initialisation incorrect. There shall be no implicit floating-integral 107 S Type mismatch in ternary expression. 5-0-5 Required conversions. 109 S Array subscript is not integral. 435 S Float/integer conversion without cast. 458 S Implicit conversion: actual to formal param (MR).

101 S Function return type inconsistent. An implicit integral or floating-point conversion 445 S Narrower float conversion without cast. 5-0-6 Required shall not reduce the size of the underlying 446 S Narrower int conversion without cast. type. 458 S Implicit conversion: actual to formal param (MR). 488 S Value outside range of underlying type. There shall be no explicit floating-integral 441 S Float cast to non-float. 5-0-7 Required conversions of a cvalue expression. 444 S Integral type cast to non-integral. An explicit integral or floating-point conversion 332 S Widening cast on complex integer expression (MR). 5-0-8 Required shall not increase the size of the underlying 333 S Widening cast on complex float expression (MR). An explicit integral conversion shall not 442 S Signed integral type cast to unsigned. 5-0-9 Required change the signedness of the underlying type 443 S Unsigned integral type cast to signed. If the bitwise operators ~ and Type conversion without cast. signed char and unsigned char type shall only 431 S Char used instead of (un)signed char. 5-0-12 Required be used for the storage and use of numeric 432 S Inappropriate type - should be plain char. values. 433 S Type conversion without cast. The condition of an if-statement and the 5-0-13 Required condition of an iteration-statement shall have 114 S Expression is not Boolean. type bool. The first operand of a conditional-operator shall 5-0-14 Required 114 S Expression is not Boolean. have type bool. Array indexing shall be the only form of pointer 436 S Declaration does not specify an array. 5-0-15 Required arithmetic. 567 S Pointer arithmetic is not on array. 47 S Array bound exceeded. 436 S Declaration does not specify an array. A pointer operand and any pointer resulting 692 S Array index is negative. 5-0-16 Required from pointer arithmetic using that operand shall 64 X Array bound exceeded at call. both address elements of the same array. 68 X Parameter indexing array too big at call. 69 X Global array bound exceeded at use. 72 X Parameter indexing array too small at call. Subtraction between pointers shall only be 5-0-17 Required applied to pointers that address elements of the 438 S Pointer subtraction not addressing one array. same array.

>, >=, = used on different object pointers. same array. The declaration of objects shall contain no 5-0-19 Required 80 S Pointer indirection exceeds 2 levels. more than two levels of pointer indirection. Non-constant operands to a binary bitwise 5-0-20 Required 535 S Binary bitwise op with different types. operator shall have the same underlying type. 50 S Use of shift operator on signed type. Bitwise operators shall only be applied to 5-0-21 Required 120 S Use of bit operator on signed type. operands of unsigned underlying type. 345 S Bit operator with floating point operand. Each operand of a logical && or || shall be a 5-2-1 Required 49 S Logical conjunctions need brackets. postfix-expression. A pointer to a virtual base class shall only be 5-2-2 Required cast to a pointer to a derived class by means of 448 S Base class pointer cast to derived class. dynamic_cast. Casts from a base class to a derived class 5-2-3 Advisory 551 S Cast from base to derived for polymorphic type (MR). should not be performed on polymorphic types. C-style casts (other than void casts) and 5-2-4 Required functional notation casts (other than explicit 306 S Use of C type cast. constructor calls) shall not be used. A cast shall not remove any const or volatile 203 S Cast on a constant value. 5-2-5 Required qualification from the type of a pointer or 242 S Use of const_cast. reference. 344 S Cast on volatile value. A cast shall not convert a pointer to a function 576 S Function pointer is of wrong type. 5-2-6 Required to any other pointer type, including a pointer to 606 S Cast involving function pointer. function type. An object with pointer type shall not be 94 S Casting operation on a pointer. 5-2-7 Required converted to an unrelated pointer type, either 95 S Casting operation to a pointer. directly or indirectly. 554 S Cast to an unrelated type. An object with integer type or pointer to void 440 S Cast from integral type to pointer. 5-2-8 Required type shall not be converted to an object with 540 S Cast from pointer to void to pointer. A cast should not convert a pointer type to an 5-2-9 Advisory 439 S Cast from pointer to integral type. integral type. The increment (++) and decrement (--) 5-2-10 Advisory operators should not be mixed with other 30 S Deprecated usage of ++ or -- operators found. operators in an expression. The comma operator, && operator and the || 5-2-11 Required 211 S Overloaded &&, || or comma. operator shall not be overloaded.

An identifier with array type passed as a 459 S Array passed as actual parameter. 5-2-12 Required function argument shall not decay to a 534 S Array has decayed to pointer. Each operand of the ! operator, the logical && 5-3-1 Required 114 S Expression is not Boolean. or the logical || operators shall have type bool. The unary minus operator shall not be applied 5-3-2 Required to an expression whose underlying type is 52 S Unsigned expression negated. unsigned. 5-3-3 Required The unary & operator shall not be overloaded. 508 S Operator & overloaded. Evaluation of the operand to the sizeof 5-3-4 Required 54 S Sizeof operator with side effects. operator shall not contain side effects. The right hand operand of a shift operator 51 S Shifting value too far. 5-8-1 Required shall lie between zero and one less than the 403 S Negative (or potentially negative) shift. 35 D Expression has side effects. The right hand operand of a logical && or || 1 Q Call has execution order dependant side effects. 5-14-1 Required operator shall not contain side effects. 406 S Use of ++ or -- on RHS of && or || operator. 408 S Volatile variable accessed on RHS of && or ||. The semantic equivalence between a binary 5-17-1 Required operator and its assignment operator form shall be preserved. 5-18-1 Required The comma operator shall not be used. 53 S Use of comma operator. Evaluation of constant unsigned integer 493 S Numeric overflow. 5-19-1 Advisory expressions should not lead to wrap-around. 494 S Numeric underflow. Assignment operators shall not be used in 9 S Assignment operation in expression. 6-2-1 Required sub-expressions. 132 S Assignment operator in boolean expression. Floating-point expressions shall not be 6-2-2 Required directly or indirectly tested for equality or 56 S Equality comparison of floating point. inequality. Before preprocessing, a null statement shall only occur on a line by itself; it may be 6-2-3 Required followed by a comment, provided that the first 58 S Null statement found. character following the null statement is a white-space character. The statement forming the body of a switch, 11 S No brackets to loop body (added by Testbed). 6-3-1 Required while, do...while or for statement shall be a 428 S No {} for switch (added by Testbed). An if ( condition ) construct shall be followed by a compound statement. The else keyword shall 6-4-1 Required 12 S No brackets to then/else (added by Testbed). be followed by either a compound statement, or another if statement.

All if ... else if constructs shall be terminated 59 S Else alternative missing in if. 6-4-2 Required with an else clause. 477 S Empty else clause following else if. A switch statement shall be a well-formed 323 S Switch has more than one default case. 6-4-3 Required switch statement. 385 S MISRA switch statement syntax violation. A switch-label shall only be used when the 6-4-4 Required most closely-enclosing compound statement is 245 S Case statement in nested block. the body of a switch statement. An unconditional throw or break statement shall 6-4-5 Required 62 S Switch case not terminated with break. terminate every non-empty switch-clause. 48 S No default case in switch statement. The final clause of a switch statement shall be 6-4-6 Required 322 S Default is not last case of switch. the default-clause. 410 S Switch empty default has no comment (MR). The condition of a switch statement shall not 6-4-7 Required 121 S Use of boolean expression in switch. have bool type. Every switch statement shall have at least one 60 S Empty switch statement. 6-4-8 Required case-clause. 61 S Switch contains default only. A for loop shall contain a single loop-counter 39 S Unsuitable type for loop variable. 6-5-1 Required which shall not have floating type. 542 S Extra loop control variable is not bool. If loop-counter is not modified by -- or ++, then, 6-5-2 Required within condition, the loop-counter shall only be 510 S Loop counter increment and operator defect. used as an operand to or >=. The loop-counter shall not be modified within 55 D Modification of loop counter in loop body. 6-5-3 Required condition or statement. 73 D Predicate variable modified in condition. The loop-counter shall be modified by one of: -- 6-5-4 Required , ++, -=n, or +=n; where n remains constant for 271 S For loop incrementation is not simple. the duration of the loop. A loop-control-variable other than the loop- 6-5-5 Required counter shall not be modified within condition or 537 S Extra loop control variable changed. expression. A loop-control-variable other than the loop- 66 D Non boolean control variable modified in loop. 6-5-6 Required counter which is modified in statement shall 542 S Extra loop control variable is not bool. have type bool. Any label referenced by a goto statement shall 1 J Unreachable Code found. 6-6-1 Required be declared in the same block, or in a block 511 S Jump into nested block. enclosing the goto statement. The goto statement shall jump to a label 6-6-2 Required 509 S goto label is backwards. declared later in the same function body. The continue statement shall only be used 32 S Use of continue statement. 6-6-3 Required within a well-formed for loop. 65 X continue in ill-formed loop (MR).

For any iteration statement there shall be no 6-6-4 Required more than one break or goto statement used 409 S More than one break or goto statement in loop. for loop termination. A function shall have a single point of exit at 6-6-5 Required 7 C Procedure has more than one exit point. the end of the function. 59 D Parameter should be declared const. 78 D Global variable should be declared const. A variable which is not modified shall be const 7-1-1 Required 93 D Local variable should be declared const. qualified. 119 D Pointer param should be declared const pointer. 603 S Parameter should be declared * const. A pointer or reference parameter in a function shall be declared as pointer to const or 7-1-2 Required 120 D Pointer param should be declared pointer to const. reference to const if the corresponding object is not modified. An expression with enum underlying type 7-2-1 Required shall only have values corresponding to the 411 S Inappropriate value assigned to enum. enumerators of the enumeration. The global namespace shall only contain 7-3-1 Required main, namespace declarations and extern "C" 517 S At least one declaration in global namespace. declarations. The identifier main shall not be used for a 7-3-2 Required 362 S main program in a namespace. function other than the global function main. There shall be no unnamed namespaces in 7-3-3 Required 512 S Use of unnamed namespace. header files. 7-3-4 Required using-directives shall not be used. 513 S Use of using directive. Multiple declarations for an identifier in the 7-3-5 Required same namespace shall not straddle a using- 518 S Using declaration is straddled by declarations. declaration for that identifier. using-directives and using-declarations 7-3-6 Required (excluding class scope or function scope using- 514 S Using directive or declaration in header. declarations) shall not be used in header files. 7-4-1 Document All usage of assembler shall be documented. 17 S Code insert found. Assembler instructions shall only be introduced 7-4-2 Required 516 S Assembler does not use asm declaration. using the asm declaration. Assembly language shall be encapsulated and 7-4-3 Required 88 S Procedure is not pure assembler. isolated. A function shall not return a reference or a 42 D Local pointer returned in function result. 7-5-1 Required pointer to an automatic variable (including 564 S Reference assignment to wider scope. parameters), defined within the function.

The address of an object with automatic 77 D Local structure returned in function result. storage shall not be assigned to another object 7-5-2 Required that may persist after the first object has 71 S Pointer assignment to wider scope. ceased to exist. 565 S Assignment to wider scope. A function shall not return a reference or a 7-5-3 Required pointer to a parameter that is passed by 519 S Return of reference parameter. reference or const reference. Functions should not call themselves, either 6 D Recursion in procedure calls found. 7-5-4 Advisory directly or indirectly. 1 U Inter-file recursion found. An init-declarator-list or a member-declarator- 8-0-1 Required list shall consist of a single init-declarator or 515 S More than one variable in declaration (MR). member-declarator respectively. Parameters in an overriding virtual function shall either use the same default arguments as 8-3-1 Required 364 S Inherited default parameter redefined. the function they override, or else shall not specify any default arguments. Functions shall not be defined using the ellipsis 8-4-1 Required 41 S Ellipsis used in procedure parameter list. notation. The identifiers used for the parameters in a re- 8-4-2 Required declaration of a function shall be identical to 36 D Prototype and definition name mismatch. those in the declaration. All exit paths from a function with non-void 2 D Function does not return a value on all paths. 8-4-3 Required return type shall have an explicit return 36 S Function has no return statement. statement with an expression. 66 S Function with empty return expression. A function identifier shall either be used to call 8-4-4 Required 99 S Function use is not a call. the function or it shall be preceded by & . 53 D Attempt to use uninitialised pointer. All variables shall have a defined value before 8-5-1 Required 69 D UR anomaly, variable used before assignment. they are used. 631 S Declaration not reachable. Braces shall be used to indicate and match 105 S Initialisation brace { } fault. 8-5-2 Required the structure in the non-zero initialization of 397 S Array initialisation has insufficient items. In an enumerator list, the = construct shall not be used to explicitly initialize members other 8-5-3 Required 85 S Incomplete initialisation of enumerator. than the first, unless all items are explicitly initialized. const member functions shall not return non- 9-3-1 Required 392 S Class data accessible thru non const member. const pointers or references to class-data. Member functions shall not return non-const 9-3-2 Required 671 S Class data accessible thru non const handle. handles to class-data.

If a member function can be made static then 46 D Member function may be declared const. 9-3-3 Required it shall be made static, otherwise if it can be 79 D Member function may be declared static. 9-5-1 Required Unions shall not be used. 74 S Union declared. When the absolute positioning of bits 42 S Use of bit field in structure declaration. 9-6-1 Document representing a bit-field is required, then the 328 S Non bit field member in bitfield struct. Bit-fields shall be either bool type or an 9-6-2 Required 520 S Bit field is not bool or explicit integral. explicitly unsigned or signed integral type. 520 S Bit field is not bool or explicit integral. 9-6-3 Required Bit-fields shall not have enum type. 536 S Enum type in bit field (MR). Named bit-fields with signed integer type shall 9-6-4 Required 72 S Signed bit field less than 2 bits wide. have a length of more than one bit. Classes should not be derived from virtual 10-1-1 Advisory 521 S Class derived from virtual base class. bases. A base class shall only be declared virtual if it 10-1-2 Required 543 S Virtual base not in diamond hierarchy. is used in a diamond hierarchy. An accessible base class shall not be both 10-1-3 Required 357 S Base class is mixed virtual and non virtual. virtual and non-virtual in the same hierarchy. All accessible entity names within a multiple 10-2-1 Advisory 555 S Base class member name not unique. inheritance hierarchy should be unique. There shall be no more than one definition of 10-3-1 Required each virtual function on each path through the 559 S Virtual member defined more than once. inheritance hierarchy. Each overriding virtual function shall be 10-3-2 Required 214 S Member not declared virtual. declared with the virtual keyword. A virtual function shall only be overridden by a 10-3-3 Required pure virtual function if it is itself declared as 544 S Member re-declared pure. pure virtual. Member data in non-POD class types shall be 11-0-1 Required 202 S Class data is not explicitly private. private. 92 D C'tor/d'tor calls virtual function. An object's dynamic type shall not be used 12-1-1 Required 467 S Virtual member called in ctor/dtor. from the body of its constructor or destructor. 561 S Use of dynamic type in c'tor/d'tor. All constructors of a class should explicitly call 12-1-2 Advisory a constructor for all of its immediate base 528 S Base class constructor omitted (added by Testbed). classes and all virtual base classes. All constructors that are callable with a single 12-1-3 Required argument of fundamental type shall be 393 S Single parameter constructor not 'explicit'. declared explicit.

A copy constructor shall only initialize its base 12-8-1 Required classes and the non-static members of the 529 S Static member initialised/assigned in constructor. class of which it is a member. The copy assignment operator shall be 12-8-2 Required declared protected or private in an abstract 522 S Public assign operator in abstract class. class. A non-member generic function shall only be 14-5-1 Required declared in a namespace that is not an associated namespace. A copy constructor shall be declared when 14-5-2 Required there is a template constructor with a single 532 S No copy ctor for templated copy ctor. parameter that is a generic parameter. A copy assignment operator shall be declared 14-5-3 Required when there is a template assignment operator 533 S No assgnmt optor for templated assgmnt op. with a parameter that is a generic parameter. In a class template with a dependent base, any name that may be found in that 14-6-1 Required 547 S Base member not qualified. dependent base shall be referred to using a qualified-id or this-> The function chosen by overload resolution 14-6-2 Required shall resolve to a function declared previously 546 S Overload resolution could be forward. in the translation unit. All class templates, function templates, class 76 D Procedure is not called or referenced in code analysed. 14-7-1 Required template member functions and class 538 S Template class/function/member not instantiated. For any given template specialization, an explicit instantiation of the template with the 14-7-2 Required 558 S Template may lead to ill-formed program. template-arguments used in the specialization shall not render the program ill-formed. All partial and explicit specializations for a 14-7-3 Required template shall be declared in the same file as the declaration of their primary template. Overloaded function templates shall not be 14-8-1 Required 539 S Specialised overloaded templated function. explicitly specialized. The viable function set for a function call should either contain no function 14-8-2 Advisory specializations, or only contain function specializations.

Exceptions shall only be used for error 15-0-1 Document handling. An exception object should not have pointer 15-0-2 Advisory 523 S Exception type is pointer. type. Control shall not be transferred into a try or 15-0-3 Required catch block using a goto or a switch 524 S Jump into try or catch statement. statement. The assignment-expression of a throw 15-1-1 Required statement shall not itself cause an exception 557 S Function call can generate throw exception. to be thrown. 15-1-2 Required NULL shall not be thrown explicitly. 525 S throw with explicit NULL. An empty throw (throw;) shall only be used in 15-1-3 Required 526 S Empty throw is not in catch statement. the compound-statement of a catch handler. Exceptions shall be raised only after start-up 15-3-1 Required 557 S Function call can generate throw exception. and before termination of the program. There should be at least one exception 15-3-2 Advisory handler to catch all otherwise unhandled 527 S No master exception handler. exceptions Handlers of a function-try-block implementation of a class constructor or 15-3-3 Required 549 S Catch in c'tor/d'tor references nonstatic member. destructor shall not reference non-static members from this class or its bases. Each exception explicitly thrown in the code 56 D Throw found with no catch in scope. 15-3-4 Required shall have a handler of a compatible type in 71 D No matching catch for throw in called function. A class type exception shall always be caught 15-3-5 Required 455 S Catch is not by reference. by reference. Where multiple handlers are provided in a single try-catch statement or function-try- 15-3-6 Required block for a derived class and some or all of its 556 S Wrong order of catches for derived class. bases, the handlers shall be ordered most- derived to base class. Where multiple handlers are provided in a single try-catch statement or function-try- 15-3-7 Required 541 S Catch-all is not last catch. block, any ellipsis (catch-all) handler shall occur last.

If a function is declared with an exception- specification, then all declarations of the same 15-4-1 Required function (in other translation units) shall be declared with the same set of type-ids.

A class destructor shall not exit with an 15-5-1 Required 453 S Throw found in destructor. exception. Where a function's declaration includes an exception-specification, the function shall only 15-5-2 Required be capable of throwing exceptions of the indicated type(s). The terminate() function shall not be called 15-5-3 Required implicitly. #include directives in a file shall only be 75 S Executable code before an included file. 16-0-1 Required preceded by other preprocessor directives or 338 S #include preceded by non preproc directives. comments. Macros shall only be #define'd or #undef'd in 67 S #define used in a block. 16-0-2 Required the global namespace. 426 S #undef used in a block. 68 S #undef used. 16-0-3 Required #undef shall not be used. 426 S #undef used in a block. 16-0-4 Required Function-like macros shall not be defined. 340 S Use of function like macro. Arguments to a function-like macro shall not 16-0-5 Required contain tokens that look like preprocessing 341 S Preprocessor construct as macro parameter. directives. In the definition of a function-like macro, each instance of a parameter shall be enclosed in 16-0-6 Required 78 S Macro parameter not in brackets. parentheses, unless it is used as the operand of # or ##. Undefined macro identifiers shall not be used in 16-0-7 Required #if or #elif preprocessor directives, except as 337 S Undefined macro variable in #if. operands to the defined operator. If the # token appears as the first token on a 147 S Spurious characters after preprocessor directive. 16-0-8 Required line, then it shall be immediately followed by a 342 S Extra chars after preprocessor directive. preprocessing token. The defined preprocessor operator shall only 335 S Operator defined contains illegal items. 16-1-1 Required be used in one of the two standard forms. 336 S #if expansion contains define operator. All #else, #elif and #endif preprocessor 126 S A #if has no #endif in the same file. 16-1-2 Required directives shall reside in the same file as the #if 343 S #else has no #if, etc in the same file. or #ifdef directive to which they are related.

255 S Found #if, #ifdef, #else, #elif . 272 S Found #ifndef (ref. removed). The pre-processor shall only be used for file 16-2-1 Required 273 S Found #define. inclusion and include guards. 307 S Use of #line, #error preprocessor directives. 340 S Use of function like macro. C++ macros shall only be used for include 16-2-2 Required guards, type qualifiers, or storage class 79 S Macro contains unacceptable items. specifiers. 16-2-3 Required Include guards shall be provided. 243 S Included file not protected with #define. The ', ", /* or // characters shall not occur in a 16-2-4 Required 100 S #include filename is non conformant. header file name. The \ character should not occur in a header 100 S #include filename is non conformant. 16-2-5 Advisory file name. 339 S #include directive with illegal items. 292 S No space between #include and filename. The #include directive shall be followed by 16-2-6 Required 339 S #include directive with illegal items. either a or "filename" sequence. 427 S Filename in #include not in or " ". There shall be at most one occurrence of the 16-3-1 Required 76 S More than one of # or ## in a macro. # or ## operators in a single macro definition. 16-3-2 Advisory The # and ## operators should not be used. 125 S Use of ## or # in a macro. All uses of the #pragma directive shall be 16-6-1 Document 69 S #pragma used. documented. 44 S Use of banned function, type or variable. Reserved identifiers, macros and functions in 68 S #undef used. 17-0-1 Required the standard library shall not be defined, 86 S Attempt to define reserved word. redefined or undefined. 156 S Use of 'defined' keyword in macro body. 219 S User name starts with underscore. The names of standard library macros and 17-0-2 Required 218 S Name is used in standard libraries. objects shall not be reused. The names of standard library functions shall 17-0-3 Required 218 S Name is used in standard libraries. not be overridden. 17-0-4 Document All library code shall conform to MISRA C++. The setjmp macro and the longjmp function 17-0-5 Required 43 S Use of setjmp/longjmp. shall not be used. 18-0-1 Required The C library shall not be used. 130 S Included file is not permitted. The library functions atof, atoi and atol from 18-0-2 Required 44 S Use of banned function, type or variable. library shall not be used.

The library functions abort, exit, getenv and 18-0-3 Required system from library shall not be 122 S Use of abort, exit, etc. used. The time handling functions of library 18-0-4 Required 130 S Included file is not permitted. shall not be used. The unbounded functions of library 18-0-5 Required 130 S Included file is not permitted. shall not be used. 18-2-1 Required The macro offsetof shall not be used. 44 S Use of banned function, type or variable. Dynamic heap memory allocation shall not be 18-4-1 Required 44 S Use of banned function, type or variable. used. The signal handling facilities of shall 18-7-1 Required 130 S Included file is not permitted. not be used. 19-3-1 Required The error indicator errno shall not be used. 44 S Use of banned function, type or variable. The stream input/output library shall 27-0-1 Required 130 S Included file is not permitted. not be used.

General Compliance Notes

Enhanced Enforcement: LDRA checks additional cases to those specified by the mapped rule for enhanced safety and security. Fully Implemented: LDRA checks all statically checkable aspects of the mapped rule. Partially Implemented: LDRA checks certain aspects of the rule.

The assessment of whether a rule is fully or partially implemented is based on whether the mapped LDRA standards cover all statically checkable aspects of the rule with a high level of coverage or only cover certain statically checkable aspects of the rule. If a rule is undecidable then this assessment is based on what it is deemed reasonable for a static analysis tool to check.

LDRA Ltd. reserves the right to change any specifications contained within this document without prior notice. The document was deemed correct at time of distribution.

  • Lecture Notes on Types for Part II of the Computer Science Tripos
  • Open C++ Tutorial∗
  • Let's Get Functional
  • Run-Time Type Information and Incremental Loading in C++
  • Kodak Color Control Patches Kodak Gray
  • 1 Simply-Typed Lambda Calculus
  • Query Rewriting Using Views in a Typed Mediator
  • Problem Solving with Programming Course Material
  • Solutions to Exercises
  • The Gaudi Reflection Tool Crash Course
  • Static Reflection
  • Polymorphic Subtyping in O'haskell
  • CS 6110 S18 Lecture 23 Subtyping 1 Introduction 2 Basic Subtyping Rules
  • Generic Programming in OCAML
  • Simply Typed Lambda Calculus Most Programming Languages Used for Serious Software Development Are Typed Languages
  • Type Theory & Functional Programming
  • A Pure Embedding of Roles Exploring 4-Dimensional Dispatch for Roles in Structured Contexts
  • Type Systems, Type Inference, and Polymorphism
  • Parametric Polymorphism, Records, and Subtyping Lecture 15 Tuesday, March 22, 2016 1 Parametric Polymorphism
  • The Typed Racket Guide
  • Idris 2: Quantitative Type Theory in Practice
  • Pybind11 Documentation
  • First-Class Polymorphism with Type Inference
  • High-Level Language
  • A Standard Functions
  • COMP 105 Homework: Type Systems COMP 105 Homework: Type Systems
  • Architectural Katas
  • Introduction to Type Systems
  • First-Class Functions • Reading: Appel 15.1-15.6 27 Apr 01
  • Lecture 14 Generic Data Structures
  • The Opencl™ C 2.0 Specification
  • Lab 9 - CMPS 1044 Computer Science I Functions
  • Programming in ANSI C
  • Defining Functions
  • Neural Nets Can Learn Function Type Signatures from Binaries
  • From Structures and Functors to Modules and Units
  • Coverity Support for MISRA Coding Standards
  • Gradual Typing for First-Class Classes∗
  • Mypy Documentation Release 0.920+Dev.209A7193feb4bbfa38d09232b0a5a916e9d2e605.Dirty
  • First-Class Functions for First-Order Database Engines
  • N4818 Date: 2019-06-17 Revises: N4766 Reply To: David Sankel [email protected]
  • Sml-Intro.Pdf
  • Introduction to C Language
  • The Simple Essence of Algebraic Subtyping Principal Type Inference with Subtyping Made Easy (Functional Pearl)
  • Theorems About Programming Languages in ACL2
  • Programming Language Theory
  • The Jack Programming Language
  • A Gradual Type System for Elixir
  • C and C++ Functions Function Type-System Nasties Recursion
  • Introduction to Type Theory
  • Extensible Programming with First-Class Cases
  • 1 Records 2 Subtyping
  • Do Not Fear First Class Functions
  • Automatic Integer Error Repair with Proper-Type Inference
  • Type Inference for Variable Definitions and Function Returns
  • Project Overview 1 Introduction 2 Langf
  • GNU Compiler Collection Internals
  • A Theory of Type Polymorphism in Programming
  • CSE341: Programming Languages Lecture 24 Subtyping
  • Introspective C++
  • Basic Principles of Computer Programming in C
  • Functions in Javascript Are Objects
  • LECTURE NOTE on PROGRAMMING in “C”
  • SML Language Features Value Declaration Function Declaration
  • Guidelines for the Use of the C++14 Language in Critical and Safety-Related Systems AUTOSAR AP Release 17-10
  • Type Classes
  • Nl2type: Inferring Javascript Function Types from Natural Language Information
  • 18: Semantic Analysis
  • Type Systems As Macros Comp Le * a T * Te N * Te a Is W S E * E N L L C O
  • C++ Technical Specification — Extensions for Reflection
  • Simply-Typed Lambda Calculus CS 152 (Spring 2020)
  • 'Sequences' in Ocaml
  • An Extensible Dynamic Linker For
  • First-Class Functions
  • Subtyping 11.1 Lecture Overview
  • Type Inference for Variable Definitions and Function Returns Jens Gustedt
  • Towards Efficient Reflective Object-Oriented Languages
  • Types 1 Static Properties of Programs 2 Types
  • Arduino Programming Notebook
  • The Racket Foreign Interface
  • Static and Strong Typing for Extended Mathematica Peter Fritzson
  • Safe Programming with Pointers Through Stateful Views*
  • Declare Parameter Type After Function Declaration
  • MISRA C++ 2008 Mapping to Codesonar®
  • Type Inference
  • A Type Is a Set of Values
  • What Is a Function's Type? • Generally, Any Two Values of the Same Type Can Be Substituted for One Another and the Program's Type Checking Will Remain Valid
  • Haskell Cheat Sheet Strings Enumerations • "Abc" – Unicode String, Sugar for This Cheat Sheet Lays out the Fundamental Ele- • [1..10] 1, 2, , 10 ['A','B','C']
  • Tutorial on C Language Programming
  • Subclassing and Subtyping

AUTOSAR 18-10 Standard mapped to Klocwork and community C and C++ checkers - Strict

You can use the AUTOSAR C++14 Strict taxonomy to ensure compliance with the AUTOSAR C++14 Standard, release 18-10. The AUTOSAR C++14 (18-10) taxonomy detects violations of our both our Klocwork C/C++ checkers, our MISRA checkers, and our Klocwork community checkers. This taxonomy includes coverage for additional rules compared to the non-strict version.

Support Summary :

  • 228 enforced rules

Additional documentation

IMAGES

  1. Assignment Operators in C++

    assignment operators shall not be used in sub expressions

  2. Assignment Operators in C with Examples

    assignment operators shall not be used in sub expressions

  3. Operators and Types of Operators

    assignment operators shall not be used in sub expressions

  4. PPT

    assignment operators shall not be used in sub expressions

  5. PPT

    assignment operators shall not be used in sub expressions

  6. Assignment Operators & Expressions

    assignment operators shall not be used in sub expressions

VIDEO

  1. Operators in JavaScript

  2. 26 Assignment operators

  3. SE1-24 Operators and Expressions

  4. 12

  5. #11 Part 2 (Control statements, Looping statements, Popup boxes)

  6. Quick R Quiz

COMMENTS

  1. Expression assigned to a wider essential type

    8 I get the following warning from our analysis tool Composite expression assigned to a wider essential type This is the code: uint32_t result; uint8_t resolution; result = 1U << resolution; I tried the following: #define SHIFT_BY_ONE (uint8_t)1 result = SHIFT_BY_ONE << resolution;

  2. Coding Rules

    1. Assignments should not be made from within sub-expressions objc CODE_SMELL READY rank1 Assignments within sub-expressions are hard to spot and therefore make the code less readable. Ideally, sub-expressions should not have side-effects. Noncompliant Code Example if ( (str = cont.substring (pos1, pos2)).isEmpty ()) { // Noncompliant //...

  3. EXP45-C. Do not perform assignments in selection statements

    … Rule 03. Expressions (EXP) EXP45-C. Do not perform assignments in selection statements Created by Robert Seacord (Manager), last modified by Jill Britton on Apr 20, 2023 Do not use the assignment operator in the contexts listed in the following table because doing so typically indicates programmer error and can result in unexpected behavior.

  4. How to fix Misra 2012 violation , " Assignment operation in expression

    1 I am trying to clear a bit in a 32bit variable using macro. eg. #define CLEAR_BIT( VAR, BIT ) ( VAR &= ~( BIT ) ) in function, I have called macro as CLEAR_BIT(variable, 0x01 ); In this case, I am getting MISRA C - 2012 violation as " Assignment operation in the expression" " MISRA-C:2012 R.13.1, R.13.2, R.13.4 "

  5. C++ Coding Rules Supported for Code Generation

    Assignment operators shall not be used in sub-expressions. Compliant : A6-2-1: Move and copy assignment operators shall either move or respectively copy base classes and data members of a class, without any side effects. Compliant : M6-2-2: Floating-point expressions shall not be directly or indirectly tested for equality or inequality. Not ...

  6. MISRA C Coding Standards & Guidelines

    Assignment operators shall not be used in expressions that yield a Boolean value. Required Rule 13.2 Tests of a value against zero should be made explicit, unless the operand is effectively Boolean. Advisory Rule 13.3 Floating-point expressions shall not be tested for equality or inequality. Required Rule 13.4

  7. Assignment operators

    Assignment operators modify the value of the object. replaces the contents of the object is not modified). For class types, this is performed in a special member function, described in. ↑ target-expr must have higher precedence than an assignment expression.

  8. Common TypeScript issues No.1: assignments within sub-expressions

    Nº 1: assignments within sub-expressions Have you ever written a conditional and then tested it out to find that it was not behaving how you'd expected it to? Whether or not the expression in the conditional is true or false, the code inside the conditional is still running.

  9. Misra.assign.subexpr

    Assignment operator is used in sub-expression. MISRA C++ Rule 6-2-1 (required): Assignment operators shall not be used in subexpressions. ... Assignments used in a sub-expression add an additional side effect to that of the full expression, potentially resulting in a value inconsistent with developer expectations. In addition, this helps to ...

  10. MISRA C :2004 and MISRA AC AGC Coding Rules

    The Polyspace coding rules checker: Supports MISRA-C:2004 Technical Corrigendum 1 for rules 4.1, 5.1, 5.3, 6.1, 6.3, 7.1, 9.2, 10.5, 12.6, 13.5, and 15.0. Checks rules specified by MISRA AC AGC Guidelines for the Application of MISRA-C:2004 in the Context of Automatic Code Generation.

  11. Assignment in Subexpressions (GNU C Language Manual)

    In C, the order of computing parts of an expression is not fixed. Aside from a few special cases, the operations can be computed in any order. If one part of the expression has an assignment to x and another part of the expression uses x, the result is unpredictable because that use might be computed before or after the assignment.

  12. Rule 6-2-1 Assignment operators shall not be used in subexpressions

    IMHO, both are technically sub-expressions. It's either a mistake that the second one is compliant or the intent of MISRA was to add an explicit exception for declaration+initialization of block scope variables like i (x is not, so you have the side effect of changing its value + confusing it with ==). Anyway, an official clarification would be ...

  13. PEP 572

    An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as ...

  14. PDF Coverity Support for AUTOSAR Coding Standards

    A5-16-1 The ternary conditional operator shall not be used as a sub-expression. Automated Required Yes A6-2-1 Move and copy assignment operators shall either move or respectively copy base classes and data members of a class, without any side effects. Automated Required Yes A6-2-2 Expression statements shall not be explicit calls to constructors of

  15. MISRA Discussion Forums

    IMHO, both are technically sub-expressions. It's either a mistake that the second one is compliant or the intent of MISRA was to add an explicit exception for declaration+initialization of block scope variables like i (x is not, so you have the side effect of changing its value + confusing it with ==). ... > Rule 6-2-1 Assignment operators ...

  16. EXP51-J. Do not perform assignments in conditional expressions

    The assignment operator should not be used in the following contexts: if ( controlling expression) while (controlling expression) do ... while (controlling expression) for (second operand) switch (controlling expression) ?: (first operand) && (either operand) || (either operand)

  17. MISRA-C++:2008 Standards Model Summary for C++

    Assignment operators shall not be used in 9 S Assignment operation in expression. 6-2-1 Required sub-expressions. 132 S Assignment operator in boolean expression. Floating-point expressions shall not be 6-2-2 Required directly or indirectly tested for equality or 56 S Equality comparison of floating point. inequality. Before preprocessing, a ...

  18. Imagix 4D

    Assignment operators shall not be used in sub-expressions. Rule A6-2-1: Move and copy assignment operators shall either move or respectively copy base classes and data members of a class, without any side effects. Rule A6-2-2: Expression statements shall not be explicit calls to constructors of temporary objects only. Rule M6-2-2

  19. Order of evaluation of assignment subexpressions

    1 The C++11 standard (5.17, expr.ass) states that In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. With respect to an indeterminately-sequenced function call, the operation of a compound assignment is a single evaluation

  20. Avoid doing assignments in sub-expressions (C++)

    Toggle navigation CAST Appmarq. Avoid doing assignments in sub-expressions (C++) - […] Preparing Data...

  21. AUTOSAR 18-10 Standard mapped to Klocwork and community C and C++

    AUTOSAR.TERNARY.NESTED The ternary conditional operator shall not be used as a sub-expression A6-2-1 (req.) AUTOSAR.ADD.ASSIGN.OP.SIDE.EFFECT Move and copy assignment operators shall either move or respectively copy base classes and data members of a class, without any side effects ... MISRA.ASSIGN.SUBEXPR Assignment operator is used in a sub ...