2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
The scope of objects shall be restricted to functions where possible. File scope shall only be used where objects need to have either internal or external linkage. Where objects are declared at file scope MISRA C 2004 Rule 8.10 applies. It is considered good practice to avoid making identifiers global except where necessary.
Whether objects are declared at the outermost or innermost block is largely a matter of style.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
int temp;
int function() {
temp = someFunction1();
temp += someFunction2();
// ...
return temp;
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
int function() {
int temp;
temp = someFunction1();
temp += someFunction2();
// ...
return temp;
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
* MISRA C:2004, 8.7 - Objects shall be defined at block scope if they are only accessed from within a single function.
* MISRA C:2012, 8.9 - An object should be defined at block scope if its identifier only appears in a single function
* https://wiki.sei.cmu.edu/confluence/x/z9YxBQ[CERT, DCL19-C.] - Minimize the scope of variables and functions
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Move this declaration inside the body of function "xxx"
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== relates to: S806
=== on 17 Oct 2014, 13:35:01 Ann Campbell wrote:
\[~freddy.mallet] this rule overlaps the {cpp} version: RSPEC-806
=== on 17 Oct 2014, 13:35:48 Ann Campbell wrote:
Nicely done [~samuel.mercier]. Good SQALE choice too.
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]