Skip to content

Commit 00f6d6a

Browse files
jurahuljh7370nikic
authored
[NFC][CodingStandard] Require[[maybe_unused]] for unused variables in asserts (#142850)
Require using attribute `[[maybe_unused]` for assert-only variables that may be unused in non-assert enabled builds to suppress unused variable warnings. --------- Co-authored-by: James Henderson <[email protected]> Co-authored-by: Nikita Popov <[email protected]>
1 parent 3d51490 commit 00f6d6a

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

llvm/docs/CodingStandards.rst

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -591,6 +591,8 @@ rather than C-style casts. There are two exceptions to this:
591591

592592
* When casting to ``void`` to suppress warnings about unused variables (as an
593593
alternative to ``[[maybe_unused]]``). Prefer C-style casts in this instance.
594+
Note that if the variable is unused because it's used only in ``assert``, use
595+
``[[maybe_unused]]`` instead of a C-style void cast.
594596

595597
* When casting between integral types (including enums that are not strongly-
596598
typed), functional-style casts are permitted as an alternative to
@@ -1288,17 +1290,26 @@ These are two interesting different cases. In the first case, the call to
12881290
``V.size()`` is only useful for the assert, and we don't want it executed when
12891291
assertions are disabled. Code like this should move the call into the assert
12901292
itself. In the second case, the side effects of the call must happen whether
1291-
the assert is enabled or not. In this case, the value should be cast to void to
1292-
disable the warning. To be specific, it is preferred to write the code like
1293-
this:
1293+
the assert is enabled or not. In this case, the value should be defined using
1294+
the ``[[maybe_unused]]`` attribute to suppress the warning. To be specific, it is
1295+
preferred to write the code like this:
12941296

12951297
.. code-block:: c++
12961298

12971299
assert(V.size() > 42 && "Vector smaller than it should be");
12981300

1299-
bool NewToSet = Myset.insert(Value); (void)NewToSet;
1301+
[[maybe_unused]] bool NewToSet = Myset.insert(Value);
13001302
assert(NewToSet && "The value shouldn't be in the set yet");
13011303

1304+
In C code where ``[[maybe_unused]]`` is not supported, use ``void`` cast to
1305+
suppress unused variable warning as follows:
1306+
1307+
.. code-block:: c
1308+
1309+
LLVMValueRef Value = LLVMMetadataAsValue(Context, NodeMD);
1310+
assert(LLVMIsAValueAsMetadata(Value) != NULL);
1311+
(void)Value;
1312+
13021313
Do Not Use ``using namespace std``
13031314
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
13041315

0 commit comments

Comments
 (0)