== Why is this an issue?

Assigning a value inside a condition (of an `if` statement, a `for` statement, a `while`, or a `switch`) can be confusing. It assigns the value and checks it at the same time, but it is easily confused with a simple equality check with `==` and the original intention can be unclear.


[source,cpp,diff-id=1,diff-type=noncompliant]
----
  if (x = getValue()) { // Noncompliant: assigning and checking. Is it on purpose?
    doSomething();
  }
----

It is better to assign before the statement and use the condition for the check only:

[source,cpp,diff-id=1,diff-type=compliant]
----
  x = getValue();
  if (x) {
    doSomething();
  }
----

=== Exceptions

This rule ignores assignments explicitly enclosed in parentheses.

[source,cpp]
----
while ((run = keepRunning())) {
  //...
}
----

== Resources

=== Documentation

* CWE - https://cwe.mitre.org/data/definitions/481[CWE-481: Assigning instead of Comparing]

=== Standards

* CERT - https://wiki.sei.cmu.edu/confluence/x/ZNYxBQ[EXP45-C. Do not perform assignments in selection statements]

=== External coding guidelines

* MISRA C:2004, 13.1 - Assignment operators shall not be used in expressions that yield a Boolean value
* MISRA {cpp}:2008, 6-2-1 - Assignment operators shall not be used in sub-expressions
* MISRA C:2012, 13.4 - The result of an assignment operator should not be used

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

include::../highlighting.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
