error with code
cant figure out how to fix this error. here is the error code i get:
line col
11 9 [Error] statement has no effect [-Werror=unused-value]
11 9 [Error] statement is a reference, not call, to function ‘ifPrime’ [-Werror=address]
12 6 [Error] unused variable ‘value’ [-Werror=unused-variable]
help is greatly appreciated.
|
|
here is the numbers for the numbersinput file:
2529
2286
1253
1029
692
117
1984
1524
804
154
1068
626
2037
573
177
242
1676
914
1878
278
1851
2875
28
714
1492
244
297
185
50
425
395
317
345
67
221
33
19
141
40
126
76
35
11
77
36
140
105
20
9
5
Hi Ghostman513,
This program seems like a good chance to use a loop. A for loop has the following syntax:
|
|
Your conditionals for the ifPrime() function are also off.
Here is a link that will explain these things better than I can:
http://www.cplusplus.com/doc/tutorial/control/
Below is a restructured version of your program, although the ifPrime() function is still not correct:
|
|
You’re on the right track for the ifPrime function. I would use the modulus operator (%) which will return the remainder of division. EX: 15 % 2 = 1, since 15 / 2 has one as a remainder. Using that and a loop, iterate through values less than the value1 and break if value1 % loopCount equals 0. Additionally, why are there 3 values being passed to ifPrime? It only uses one of them.
Last edited on
this is for a project where they want us to test 50 numbers from an input file test them to see if they are prime and then if they are prime to put them in an output file.
In this situation, there is no need to store all the values from the file, not in an array, nor in many separate variables.
Just read a single value from the file, test whether or not it is prime, write it to the output file only if it is prime. Repeat.
Function ifprime should have a return type of bool and take a single parameter, the number being tested. Return true in the case of a prime number, otherwise return false.
bool ifPrime(int);
The errors you posted are on lines 12 and 13 of the code you posted:
11 9 [Error] statement has no effect [-Werror=unused-value]
The statement ifPrime;
does not call ifPrime, it just returns the function’s address, which is then thrown away. So the
on the program.
11 9 [Error] statement is a reference, not call, to function ‘ifPrime’ [-Werror=address]
Like I said, that statement doesn’t call function ifPrime.
12 6 [Error] unused variable ‘value’ [-Werror=unused-variable]
At line 13 you declare variable «value», but you never use it in the program.
One other bug: function names in C++ are case sensitive, so the function ifPrime() that you declare at line 6 is NOT the same as the function IfPrime that you call define at line 179
> this is for a project where they want us to test 50 numbers from an input file
> test them to see if they are prime and then if they are prime to put them in an output file.
Chervil +1
>> there is no need to store all the values from the file, not in an array, nor in many separate variables.
>> Just read a single value from the file, test whether or not it is prime,
>> write it to the output file only if it is prime. Repeat.
Something along these lines:
|
|
Topic archived. No new replies allowed.
Содержание
- Сообщения об ошибках Сообщения об ошибках периода компиляции
- MSC12-C. Detect and remove code that has no effect or is never executed
- Noncompliant Code Example
- Compliant Solution
- Noncompliant Code Example
- Compliant Solution
- Noncompliant Code Example (Assignment)
- Compliant Solution (Assignment)
- Noncompliant Code Example (Dereference)
- Compliant Solution (Dereference)
- Noncompliant Code Example (if/else if)
- Compliant Solution (if/else if)
- Compliant Solution (Conditional Side-Effects)
- Noncompliant Code Example (logical operators)
- Compliant Solution (logical operators)
- Noncompliant Code Example (Unconditional Jump)
- Compliant Solution (Unconditional Jump)
- Exceptions
- Risk Assessment
- expression has no effect error ? for loop and array
- Предупреждения компилятора по версиям компилятора
- Предупреждения, появившиеся в Visual Studio 2022 версии 17.4 (компилятор версии 19.34)
- Предупреждения, появившиеся в Visual Studio 2022 версии 17.3 (компилятор версии 19.33)
- Предупреждения, появившиеся в Visual Studio 2022 версии 17.2 (компилятор версии 19.32)
- Предупреждения, появившиеся в Visual Studio 2022 версии 17.1 (компилятор версии 19.31)
- Предупреждения, появившиеся в Visual Studio 2022 версии 17.0 (компилятор версии 19.30)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.11 (компилятор версии 19.29.30100.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.10 (компилятор версии 19.29.30000.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.9 (компилятор версии 19.28.29700.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.8 (компилятор версии 19.28.29333.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.7 (компилятор версии 19.27.29112.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.6 (компилятор версии 19.26.28805.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.5 (компилятор версии 19.25.28610.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.4 (компилятор версии 19.24.28314.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.3 (компилятор версии 19.23.28105.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.2 (компилятор версии 19.22.27905.0)
- Предупреждения, появившиеся в Visual Studio 2019 версии 16.1 (компилятор версии 19.21.27702.0)
- Предупреждения, появившиеся в Visual Studio 2019 RTW (компилятор версии 19.20.27004.0)
- Предупреждения, появившиеся в Visual Studio 2017 версии 15.8 (компилятор версии 19.15.26726.0)
- Предупреждения, появившиеся в Visual Studio 2017 версии 15.7 (компилятор версии 19.14.26428.0)
- Предупреждения, появившиеся в Visual Studio 2017 версии 15.6 (компилятор версии 19.13.26128.0)
- Предупреждения, появившиеся в Visual Studio 2017 версии 15.5 (компилятор версии 19.12.25830.0)
- Предупреждения, появившиеся в Visual Studio 2017 версии 15.3 (компилятор версии 19.11.25506.0)
- Предупреждения, появившиеся в Visual Studio 2017 RTM (компилятор версии 19.10.25017.0)
- Предупреждения, появившиеся в Visual Studio 2015 с обновлением 3 (компилятор версии 19.00.24215.1)
- Предупреждения, появившиеся в Visual Studio 2015 с обновлением 2 (компилятор версии 19.00.23918.0)
- Предупреждения, появившиеся в Visual Studio 2015 с обновлением 1 (компилятор версии 19.00.23506.0)
- Предупреждения, появившиеся в Visual Studio 2015 RTM (компилятор версии 19.00.23026.0)
- Предупреждения, появившиеся в Visual Studio 2013 (версия компилятора 18.00.21005.1)
- Предупреждения, появившиеся в Visual Studio 2012 (версия компилятора 17.00.51106.1)
- Предупреждения, появившиеся в Visual Studio 2010 (версия компилятора 16.00.40219.01)
- Предупреждения, появившиеся в Visual Studio 2008 (версия компилятора 15.00.21022.08)
- Предупреждения, появившиеся в Visual Studio 2005 (версия компилятора 14.00.50727.762)
- Предупреждения, появившиеся в Visual Studio 2003 (версия компилятора 13.10.3077)
- Предупреждения, появившиеся в Visual Studio 2002 (версия компилятора 13.00.9466)
Сообщения об ошибках Сообщения об ошибках периода компиляции
«,» expected (Нужно указать «,»).
Array bounds missing «]» (Массив ограничивает отсутствие «]»).
Array must have at least one element (Массив должен иметь по крайней мере один элемент).
Call of nonfunction (Нефункциональное обращение).
Call to function ‘function’ with no prototype (Обращение к функции «функция» без прототипа).
Code has no effect (Код не имеет эффекта).
Compound statement missing «>» (Утверждение, пропускающее «>»).
Declaration is not allowed here (Здесь не допускается объявление).
Declaration missing «;» (Отсутствие объявления «;»).
Declaration syntax error (Синтаксическая ошибка, объявление переменной).
Declaration terminated incorrectly (Объявления, завершенные неправильно).
Delete array size missing «]» (Отсутствие скобки «]»).
do-while statement missing ;OR For statement missing ; (Отсутствие утверждения do-while, или отсутствие утверждения For).
Expression syntax (Ошибка синтаксиса в выражении).
Extra parameter in call to function (Недопустимый параметр в обращении к функции).
Function call missing «)» (В обращении к функции отсутствует «)»).
Illegal initialization (Неверная инициализация).
Illegal character ‘character’ (Неверный символ » символ «).
Illegal structure operation (Неверная операция структуры).
Illegal use of pointer (Неверное использование указателя).
‘identifier’ cannot start a parameter declaration (Идентификатор не может начать объявление параметра).
‘identifier‘ is assigned a value which is never used (Идентификатор определяет значение, которое ранее не использовалось).
Invalid indirection (Недопустимый ссылка).
Lvalue required (Требуется наименование выражения (адрес переменной)).
Member identifier expected (Ожидается значение идентификатора).
Multiple declaration for ‘identifier’ (Многократные объявления для идентификатора).
Must take address of a memory location (Необходимо взять адрес расположения памяти).
Non-portable pointer conversion (Преобразования указателя не переносятся).
Not an allowed type (Недопустимый тип).
Operator «[]» missing «]» (Оператор «[]» не имеет «]»).
Overlays only supported in medium, large, and huge memory models (Оверлейные программы, поддерживаемые только в среде, большие и огромные модели памяти).
Parameter ‘parameter‘ is never used (Параметр «параметр» ранее никогда не использовался).
Size of ‘identifier’ is unknown or zero (Размер идентификатора неизвестен или нуль).
Structure required on left side of . or .* (Ошибка структуры на левой стороне, или отсутствие «*»).
Two consecutive dots (Наличие двух последовательных точек).
Too few parameters in call to ‘function’ (Несколько параметров в обращении к «функции»).
Too many initializers (Слишком много инициализаторов).
Too many error or warning messages (Слишком много ошибок или предупреждений).
Type mismatch in parameter ‘parameter‘ in call to ‘function‘ (Несоответствие типов в параметре «параметр» при обращении к «функции»).
Type mismatch in redeclaration of ‘identifier‘ (Несоответствия типов в повторном определении идентификатора).
Value of type void is not allowed (Недопустимые значения типа).
Variable ‘identifier‘ is initialized more than once (Идентификатор переменной инициализирован более одного раза).
Unable to open include file ‘filename’ (Невозможно открыть файл).
Undefined structure ‘structure’ (Неопределенная структура «структура»).
Undefined symbol ‘identifier’ (Неопределенный символ идентификатора).
Undefined symbol ‘symbol‘ in module ‘module‘ (Неопределенный символ «символ» в модуле «модуль»).
Unknown preprocessor directive: ‘identifier‘ (Неизвестны директивы препроцессора: идентификатора).
Wrong number of arguments in call of macro ‘macro‘ (Неправильное число параметров в обращении макрокоманды » макрокоманда «).
Источник
MSC12-C. Detect and remove code that has no effect or is never executed
Code that has no effect or is never executed (that is, dead or unreachable code) is typically the result of a coding error and can cause unexpected behavior. Such code is usually optimized out of a program during compilation. However, to improve readability and ensure that logic errors are resolved, it should be identified, understood, and eliminated.
Statements or expressions that have no effect should be identified and removed from code. Most modern compilers, in many cases, can warn about code that has no effect or is never executed. (See MSC00-C. Compile cleanly at high warning levels.)
Noncompliant Code Example
This noncompliant code example demonstrates how dead code can be introduced into a program [Fortify 2006]. The second conditional statement, if (s) , will never evaluate true because it requires that s not be assigned NULL , and the only path where s can be assigned a non-null value ends with a return statement.
Compliant Solution
Remediation of dead code requires the programmer to determine why the code is never executed and then to resolve the situation appropriately. To correct the preceding noncompliant code, the return is removed from the body of the first conditional statement.
Noncompliant Code Example
In this example, the strlen() function is used to limit the number of times the function s_loop() will iterate. The conditional statement inside the loop evaluates to true when the current character in the string is the null terminator. However, because strlen() returns the number of characters that precede the null terminator, the conditional statement never evaluates true.
Compliant Solution
Removing the dead code depends on the intent of the programmer. Assuming the intent is to flag and process the last character before the null terminator, the conditional is adjusted to correctly determine if the i refers to the index of the last character before the null terminator.
Noncompliant Code Example (Assignment)
In this noncompliant code example, the comparison of a to b has no effect:
This code is likely a case of the programmer mistakenly using the equals operator == instead of the assignment operator = .
Compliant Solution (Assignment)
The assignment of b to a is now properly performed:
Noncompliant Code Example (Dereference)
In this example, a pointer increment and then a dereference occur, but the dereference has no effect:
Compliant Solution (Dereference)
Correcting this example depends on the intent of the programmer. For example, if dereferencing p was a mistake, then p should not be dereferenced.
If the intent was to increment the value referred to by p , then parentheses can be used to ensure p is dereferenced and then incremented. (See EXP00-C. Use parentheses for precedence of operation.)
Another possibility is that p is being used to reference a memory-mapped device. In this case, the variable p should be declared as volatile .
Noncompliant Code Example (if/else if)
A chain of if/else if statements is evaluated from top to bottom. At most, only one branch of the chain will be executed: the first one with a condition that evaluates to true. Consequently, duplicating a condition in a sequence of if/else if statements automatically leads to dead code.
Note that duplicating a condition violates this guideline only if the duplicate conditions always behave similarly. see a compliant solution below for a condition that is textually a duplicate but behaves differently.
Compliant Solution (if/else if)
In this compliant solution, the third conditional expression has been corrected.
Compliant Solution (Conditional Side-Effects)
This code does not violate this recommendation, because even though the conditions are textually identical, they have different side effects, because the getc() function advances the stream marker.
Noncompliant Code Example (logical operators)
Using the same subexpression on either side of a logical operator is almost always a mistake. In this noncompliant code example, the rightmost subexpression of the controlling expression of each if statement has no effect.
Compliant Solution (logical operators)
In this compliant solution, the rightmost subexpression of the controlling expression of each if statement has been removed.
Noncompliant Code Example (Unconditional Jump)
Unconditional jump statements typically has no effect.
Compliant Solution (Unconditional Jump)
The continue statement has been removed from this compliant solution.
Exceptions
MSC12-EX1: In some situations, seemingly dead code may make software resilient. An example is the default label in a switch statement whose controlling expression has an enumerated type and that specifies labels for all enumerations of the type. (See MSC01-C. Strive for logical completeness.) Because valid values of an enumerated type include all those of its underlying integer type, unless enumeration constants are provided for all those values, the default label is appropriate and necessary.
MSC12-EX2: It is permissible to temporarily remove code that may be needed later. (See MSC04-C. Use comments consistently and in a readable fashion for an illustration.)
MSC12-EX3: Unused functions and variables that are part of an exported library do not violate this guideline. Likewise, code that is never executed because it is #ifdef ed out does not violate this guideline, on the grounds that it could be subsequently used in another application, or built on a different platform.
Risk Assessment
The presence of code that has no effect or is never executed can indicate logic errors that may result in unexpected behavior and vulnerabilities. Such code can be introduced into programs in a variety of ways and eliminating it can require significant analysis.
Источник
expression has no effect error ? for loop and array
I have been trying to get my head around for loops in order to store data in an array.
I read this as if a occurs start loop if a does not occur (!a) stop loop and add that a has occurred again a++.
Then store the High[i] value in the array i created High_Array[h]=Current.
Any thoughts would be greatly appreciated
hey thanks whroeder1.
I thought a; was initiating the loop as in when a happens.
Ill change it to the equivalent and try that.
The warnings have now gone so a value must be present but still no change on the chart.
a = essentially a fractal with one candle either side.
Current = High[i] so the high point of the fractal.
Shouldn’t this store the high value when a fractal occurs in the High_Array.
Then i am asking if the current fractal High_Array[0] is less than
A is a boolean. What does it mean to increment true/false? If it was false, zero becomes one or true. if it was true, one becomes two which is true.
If it enters the loop, it can never exit and your indicator is forcibly terminated after 2.5 seconds. See the log.
A is a boolean. What does it mean to increment true/false? If it was false, zero becomes one or true. if it was true, one becomes two which is true.
If it enters the loop, it can never exit and your indicator is forcibly terminated after 2.5 seconds. See the log.
Yea the log returns
Order send failed, error #0
Its a While loop though, shouldn’t it automatically switch itself off when the (a) is false and then re-enter the loop when (a) is true ?
^^Thats my understanding of it
I’m obviously wrong somewhere as it isn’t plotting anything and I’m getting the error in the log but it compiles fine ?
i appreciate your help whroeder1
General rules and best pratices of the Forum. — General — MQL5 programming forum
Messages Editor
What are Function return values ? How do I use them ? — MQL4 and MetaTrader 4 — MQL4 programming forum
Common Errors in MQL4 Programs and How to Avoid Them — MQL4 Articles
Only those functions that return a value (e.g. iClose, MarketInfo, etc.) must you call ResetLastError before in order to check after.
Hey whroeder1 my original post is posted using the code box as well ?
I understand what you are saying as i am incrementing it, the bool always has a a positive value. If it isn’t 0 (false) it will never be switched off.
However, the while loop operator documentation gives this as an example
Isn’t this exactly what i am doing ?
sorry if i am being annoying just trying to get my head around this so i can fix it ha
Источник
Предупреждения компилятора по версиям компилятора
Компилятор может подавлять предупреждения, появившиеся после указанной версии, с помощью параметра компилятора /Wv . Этот параметр удобен для управления процессом сборки, когда вы вводите новую версию набора инструментов и хотите временно отключить новые предупреждения. Этот параметр подавляет только предупреждения, но не новые сообщения об ошибках. Не подавляйте все новые предупреждения постоянно! Мы рекомендуем всегда компилировать на самом высоком регулярном уровне /W4 предупреждений , и удалить /Wv параметр в сборке, как только это будет удобно.
В следующих версиях компилятора появились новые предупреждения:
Продукт | Номер версии компилятора |
---|---|
Visual Studio 2002 | 13.00.9466 |
Visual Studio 2003 | 13.10.3077 |
Visual Studio 2005 | 14.00.50727.762 |
Visual Studio 2008 | 15.00.21022.08 |
Visual Studio 2010 | 16.00.40219.01 |
Visual Studio 2012 | 17.00.51106.1 |
Visual Studio 2013 | 18.00.21005.1 |
Visual Studio 2015 RTM | 19.00.23026.0 |
Visual Studio 2015 с обновлением 1 | 19.00.23506.0 |
Visual Studio 2015 с обновлением 2 | 19.00.23918.0 |
Visual Studio 2015 с обновлением 3 | 19.00.24215.1 |
Visual Studio 2017 RTM | 19.10.25017.0 |
Visual Studio 2017 версия 15.3 | 19.11.25506.0 |
Visual Studio 2017 версии 15.5 | 19.12.25830.0 |
Visual Studio 2017 версии 15.6 | 19.13.26128.0 |
Visual Studio 2017 версии 15.7 | 19.14.26428.0 |
Visual Studio 2017 версии 15.8 | 19.15.26726.0 |
Visual Studio 2017 версии 15.9 | 19.16.26926.0 |
Visual Studio 2019 RTM | 19.20.27004.0 |
Visual Studio 2019 версии 16.1 | 19.21.27702.0 |
Visual Studio 2019 версии 16.2 | 19.22.27905.0 |
Visual Studio 2019 версии 16.3 | 19.23.28105.0 |
Visual Studio 2019 версии 16.4 | 19.24.28314.0 |
Visual Studio 2019, версия 16.5 | 19.25.28610.0 |
Visual Studio 2019 версии 16.6 | 19.26.28805.0 |
Visual Studio 2019 версии 16.7 | 19.27.29112.0 |
Visual Studio 2019 версии 16.8 | 19.28.29333.0 |
Visual Studio 2019 версии 16.9 | 19.28.29700.0 |
Visual Studio 2019 версии 16.10 | 19.29.30000.0 |
Visual Studio 2019 версии 16.11 | 19.29.30100.0 |
Visual Studio 2022 версии 17.0 RTW | 19.30 |
Visual Studio 2022 версии 17.1 | 19.31 |
Visual Studio 2022 версии 17.2 | 19.32 |
Visual Studio 2022 версии 17.3 | 19.33 |
Visual Studio 2022 версии 17.4 | 19.34 |
В параметре можно указать только основное число, основное и вспомогательное номера, а также основной, дополнительный и номер сборки /Wv . Компилятор сообщает обо всех предупреждениях, которые соответствуют версиям, начинающимся с указанного числа. Он подавляет все предупреждения для версий, превышающих указанное число. Например, сообщает о предупреждениях, /Wv:17 появившиеся в любой версии Visual Studio 2012 или раньше, и отключает предупреждения, введенные любым компилятором из Visual Studio 2013 (версия 18) или более поздней версии. Чтобы отключить предупреждения, появившиеся в Visual Studio 2015 с обновлением 2 и более поздних версий, можно использовать . /Wv:19.00.23506 Используйте для /Wv:19.11 сообщения о предупреждениях, появившиеся в любой версии Visual Studio до Visual Studio 2017 версии 15.5, но подавляйте предупреждения, появившиеся в Visual Studio 2017 версии 15.5 и более поздних версий.
В следующих разделах перечислены предупреждения, появившиеся в каждой версии Visual C++, которые можно отключить с помощью параметра компилятора /Wv . Параметр /Wv не может подавлять предупреждения, которые отсутствуют в списке, которые предшествовали указанным версиям компилятора.
Предупреждения, появившиеся в Visual Studio 2022 версии 17.4 (компилятор версии 19.34)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.33 компилятора .
Предупреждение | Сообщение |
---|---|
C5260 | константная переменная «variable-name» имеет внутреннюю компоновку в включенном контексте файла заголовка, но внешнюю компоновку в контексте импортированной единицы заголовка; Рекомендуется объявить его » inline «, если он будет совместно использоваться в единицах перевода, или » static «, чтобы выразить намерение использовать его локально для этой единицы перевода |
C5261 | Целочисленный тип не может представлять все значения перечислителя в перечислении «enum-name« |
C5262 | здесь происходит неявное падение; Вам не хватает break заявления? Используется [[fallthrough]] , break если оператор намеренно опущен между вариантами |
C5263 | Вызов » std::move » для временного объекта предотвращает удаление копирования |
C5264 | «variable-name«: » const » переменная не используется |
Предупреждения, появившиеся в Visual Studio 2022 версии 17.3 (компилятор версии 19.33)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.32 компилятора .
Предупреждение | Сообщение |
---|---|
C5259 | «специализированный тип«: для явной специализации требуется «шаблон <>« |
Предупреждения, появившиеся в Visual Studio 2022 версии 17.2 (компилятор версии 19.32)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.31 компилятора .
Предупреждение | Сообщение |
---|---|
C4983 | «/analyze:sarif:hashname» игнорируется, так как аргумент для «/analyze:log» является одним файлом, а не каталогом |
C5081 | Безопасное горячее исправление не поддерживается в /GENPROFILE, /FASTGENPROFILE или /LTCG:PGI, отключая безопасное горячее исправление. |
C5255 | Обнаружен неуправляемый двунаправленный символ: «U+XXXX» |
C5256 | «перечисление«: неопределяющее объявление перечисления с фиксированным базовым типом разрешено только в виде автономного объявления. |
C5257 | «enumeration«: перечисление ранее было объявлено без фиксированного базового типа |
C5258 | Для этого использования не требуется явное запись символа |
C5300 | «#pragma omp atomic»: левый операнд оператора должен соответствовать левой части выражения assignment-expression |
C5301 | «#pragma omp для»: «символ» увеличивается, а условие цикла использует «сравнение«; неоконклюционный цикл? |
C5302 | «#pragma omp для»: «символ» уменьшается, а условие цикла использует «сравнение«; неоконклюционный цикл? |
Предупреждения, появившиеся в Visual Studio 2022 версии 17.1 (компилятор версии 19.31)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.30 компилятора .
Предупреждение | Сообщение |
---|---|
C5251 | Имя сегмента изменилось после включения заголовка |
C5253 | Нелоклайская лямбда-выражения не может иметь запись по умолчанию |
C5254 | Для функции языка «terse static assert» требуется флаг компилятора » /std:c++17 « |
Предупреждения, появившиеся в Visual Studio 2022 версии 17.0 (компилятор версии 19.30)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.29 компилятора .
Предупреждение | Сообщение |
---|---|
C5244 | «#include файла» в представлении модуля «имя_модуля-1» отображается ошибочно. Рекомендуется переместить директиву перед объявлением модуля или заменить текстовое включение на «import ;». |
C5245 | «function«: удалена функция без ссылок с внутренней компоновкой |
C5246 | «member«: инициализация подобъекта должна быть заключена в фигурные скобки |
C5249 | Bitfield типа «enumeration_name» имеет именованные перечислители со значениями, которые не могут быть представлены в заданной ширине битового поля «bitfield_width«. |
C5250 | «function_name«: встроенная функция не объявлена. |
C5252 | Несколько разных типов привели к одному и тому же хэш-значению типа XFG; PDB будет записывать сведения только для одного из них |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.11 (компилятор версии 19.29.30100.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.29.30099 компилятора .
Предупреждение | Сообщение |
---|---|
C5247 | section ‘section-name‘ зарезервирован для динамической инициализации C++. Создание раздела вручную помешает динамической инициализации C++ и может привести к неопределенному поведению. |
C5248 | section ‘section-name‘ зарезервирован для динамической инициализации C++. Переменные, помещенные вручную в раздел, могут быть оптимизированы, и их порядок относительно созданных компилятором динамических инициализаторов не указан |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.10 (компилятор версии 19.29.30000.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.28 компилятора .
Предупреждение | Сообщение |
---|---|
C5233 | явный лямбда-захват «идентификатор» не используется |
C5234 | ошибка файловой системы: «filename» не является допустимым именем заголовка; Игнорируя |
C5235 | Ошибка анализа JSON: проблема; игнорирование «filename« |
C5236 | Неправильно сформированный JSON: проблема; игнорирование «filename« |
C5237 | не удается разрешить запись блока заголовка «string» в файл заголовка в «filename«; игнорирование записи |
C5238 | ошибка файловой системы: не удается открыть имя файла для чтения; Игнорируя |
C5239 | «Symbol«: потенциально вызываемая функция, вызываемая из функции, объявленной __declspec(nothrow) . Если возникает исключение, может возникнуть неопределенное поведение. |
C5240 | ‘attribute-string‘: атрибут игнорируется в этой синтаксической позиции |
C5241 | Использование » /exportHeader » для поиска имени заголовка не рекомендуется; предпочитать » /headerName:arg-1 arg-2=filename « |
C5242 | синтаксическая ошибка в pragma ‘pragma-name‘ |
C5243 | Type-name: использование неполного класса symbol может привести к потенциальному нарушению правила определения из-за ограничения ABI |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.9 (компилятор версии 19.28.29700.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.28.29699 компилятора .
Предупреждение | Сообщение |
---|---|
C5232 | В C++20 это сравнение вызывает «идентификатор» рекурсивно |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.8 (компилятор версии 19.28.29333.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.27 компилятора .
Предупреждение | Сообщение |
---|---|
C5072 | ASAN enabled without debug information emission. Enable debug info for better ASAN error reporting |
C5211 | ‘keyword-1’ has been deprecated; prefer using ‘keyword-2’ instead |
C5222 | ‘attribute-name’: all unscoped attribute names are reserved for future standardization |
C5223 | all attribute names in the attribute namespace ‘msvc’ are reserved for the implementation |
C5224 | all attribute names in the attribute namespace ‘a-namespace’ are reserved for future standardization |
C5225 | ‘symbol’: exported inline function defined in a private module fragment is a non-standard extension |
C5226 | ‘symbol’: exported template defined in private module fragment has no reachable instantiation |
C5227 | nonstandard extension, resolved ‘symbol’ to ‘instance’ which is not visible with /permissive- on. |
C5228 | nonstandard extension, ‘identifier’ resolved to a member of a dependent base. This lookup is not allowed under /permissive-. |
C5229 | nonstandard extension, the hidden friend function ‘function-name’ was found by name lookup which isn’t allowed under /permissive-. |
C5230 | nonstandard extension, ‘identifier’ was resolved to ‘symbol’ under /permissive. Under /permissive- it would resolve to ‘other-symbol’. |
C5231 | the expression ‘co_await promise.final_suspend()’ must be non-throwing ) |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.7 (компилятор версии 19.27.29112.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.26 компилятора .
Предупреждение | Сообщение |
---|---|
C5207 | the simple requirement asserts the validity of expression ‘e->id’. Did you mean ‘ < e >-> id’? You can suppress the warning using ‘< e->id >’ |
C5209 | the C++20 syntax for an init-capture has changed to ‘& . opt identifier initializer’ |
C5210 | ‘name’ is not a valid header unit reference; ignoring |
C5212 | ‘name’ is not a valid named reference; treating as reference to file |
C5213 | ‘name’ named reference is treated as a named partition but the name is not specified; treating as reference to file |
C5214 | applying ‘modifier’ to an operand with a volatile qualified type is deprecated in C++20 |
C5215 | ‘name’ a function parameter with a volatile qualified type is deprecated in C++20 |
C5216 | ‘name’ a volatile qualified return type is deprecated in C++20 |
C5217 | a structured binding declaration that includes volatile is deprecated in C++20 |
C5218 | destroying delete may not behave as intended when non-conforming switches ‘/Zc:sizedDealloc-‘ or ‘/Zc:alignedNew-‘ are used |
C5219 | implicit conversion from ‘type-1’ to ‘type-2’, possible loss of data |
C5220 | ‘name’: a non-static data member with a volatile qualified type no longer implies%$N that compiler generated copy/move constructors and copy/move assignment operators are not trivial |
C5221 | xfg::rename is deprecated. |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.6 (компилятор версии 19.26.28805.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.25 компилятора .
Предупреждение | Сообщение |
---|---|
C5207 | the simple requirement asserts the validity of expression ‘e->id’. Did you mean ‘ < e >-> id’? You can suppress the warning using ‘< e->id >’ |
C5208 | unnamed class used in typedef name cannot declare members other than non-static data members, member enumerations, or member classes |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.5 (компилятор версии 19.25.28610.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.24 компилятора .
Предупреждение | Сообщение |
---|---|
C5061 | the use of a comma operator as a subscript expression has been deprecated |
C5062 | enum direct list initialization between ‘type-1’ and ‘type-2’ is no longer supported |
C5063 | ‘std::is_constant_evaluated’ always evaluates to true in manifestly constant-evaluated expressions |
C5108 | __VA_OPT__ is reserved for use in variadic macros |
C5204 | ‘type-name’: class has virtual functions, but its trivial destructor is not virtual; instances of objects derived from this class may not be destructed correctly |
C5205 | delete of an abstract class ‘type-name’ that has a non-virtual destructor results in undefined behavior |
C5206 | deduced return types for coroutines is a non-standard extension |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.4 (компилятор версии 19.24.28314.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.23 компилятора .
Предупреждение | Сообщение |
---|---|
C5200 | feature ‘feature-name’ requires compiler flag ‘option-name’ |
C5201 | a module declaration can appear only at the start of a translation unit unless a global module fragment is used |
C5202 | a global module fragment can only contain preprocessor directives |
C5203 | a parenthesized declarator name after ‘explicit’ will be considered an explicit-specifier in C++20 |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.3 (компилятор версии 19.23.28105.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.22 компилятора .
Предупреждение | Сообщение |
---|---|
C4856 | ‘value’ is not a valid argument for ‘/d1initAll:FillPattern’ (value must be between 0 and 255). Command-line flag ignored |
C4857 | C++/CLI mode does not support C++ versions newer than C++17; setting language to /std:c++17 |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.2 (компилятор версии 19.22.27905.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.21 компилятора .
Предупреждение | Сообщение |
---|---|
C4855 | implicit capture of ‘this’ via ‘[=]’ is deprecated in ‘version’ |
C5054 | operator ‘operator-name’: deprecated between enumerations of different types |
C5055 | operator ‘operator-name’: deprecated between enumerations and floating-point types |
C5056 | operator ‘operator-name’: deprecated for array types |
C5057 | header unit reference to ‘name’ already exists. Ignoring header unit ‘header-name’ |
C5058 | file system error: cannot find header file ‘file-name’ for header unit ‘unit-name’ |
C5059 | runtime checks and address sanitizer is not currently supported — disabling runtime checks |
C5060 | /Qpar and address sanitizer not currently supported — disabling auto-parallelization |
Предупреждения, появившиеся в Visual Studio 2019 версии 16.1 (компилятор версии 19.21.27702.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.20 компилятора .
Предупреждение | Сообщение |
---|---|
C5052 | Keyword ‘keyword-name’ was introduced in C++ and requires use of the ‘option-name’ command-line option |
C5053 | support for ‘explicit( )’ in C++17 and earlier is a vendor extension |
Предупреждения, появившиеся в Visual Studio 2019 RTW (компилятор версии 19.20.27004.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.15 компилятора .
Предупреждение | Сообщение |
---|---|
C4848 | support for standard attribute ‘no_unique_address’ in C++17 and earlier is a vendor extension |
C4854 | binding dereferenced null pointer to reference has undefined behavior |
C5051 | attribute ‘attribute-name’ requires at least ‘standard-level’; ignored |
Предупреждения, появившиеся в Visual Studio 2017 версии 15.8 (компилятор версии 19.15.26726.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.14 компилятора .
Предупреждение | Сообщение |
---|---|
C4643 | Forward declaring ‘identifier’ in namespace std is not permitted by the C++ Standard. |
C4644 | usage of the macro-based offsetof pattern in constant expressions is non-standard; use offsetof defined in the C++ standard library instead |
C4845 | ‘__declspec(no_init_all)’ is ignored if ‘/d1initall[0|1|2|3]’ was not specified on the command line |
C4846 | ‘value’ is not a valid argument for ‘/d1initall’: command-line flag ignored |
C4847 | ‘__declspec(no_init_all)’ can only be applied to a function, a class type, or a local variable: ignored |
C4866 | compiler may not enforce left-to-right evaluation order for call to ‘function’ |
C5046 | ‘function’: Symbol involving type with internal linkage not defined |
C5047 | use of nonstandard __if_exists with modules is not supported |
C5048 | Use of macro ‘macroname’ may result in non-deterministic output |
C5049 | ‘string’: Embedding a full path may result in machine-dependent output |
C5050 | Possible incompatible environment while importing module ‘module_name’: issue |
C5100 | __VA_ARGS__ is reserved for use in variadic macros |
C5101 | use of preprocessor directive in function-like macro argument list is undefined behavior |
C5102 | ignoring invalid command-line macro definition ‘value’ |
C5103 | pasting ‘token1’ and ‘token2’ does not result in a valid preprocessing token |
C5104 | found ‘string1#string2’ in macro replacement list, did you mean ‘string1″»#string2’? |
C5105 | macro expansion producing ‘defined’ has undefined behavior |
C5106 | macro redefined with different parameter names |
C5107 | missing terminating ‘char’ character |
Предупреждения, появившиеся в Visual Studio 2017 версии 15.7 (компилятор версии 19.14.26428.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.13 компилятора .
Предупреждение | Сообщение |
---|---|
C4642 | ‘issue’: could not import the constraints for generic parameter ‘parameter’ |
C5045 | Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified |
Предупреждения, появившиеся в Visual Studio 2017 версии 15.6 (компилятор версии 19.13.26128.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.12 компилятора .
Предупреждение | Сообщение |
---|---|
C5044 | An argument to command-line option option points to a path ‘path’ that does not exist |
Предупреждения, появившиеся в Visual Studio 2017 версии 15.5 (компилятор версии 19.12.25830.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.11 компилятора .
Предупреждение | Сообщение |
---|---|
C4843 | ‘type1’: An exception handler of reference to array or function type is unreachable, use ‘type2’ instead |
C4844 | ‘export module module_name;’ is now the preferred syntax for declaring a module interface |
C5039 | ‘function’: pointer or reference to potentially throwing function passed to extern C function under -EHc. Undefined behavior may occur if this function throws an exception. |
C5040 | dynamic exception specifications are valid only in C++14 and earlier; treating as noexcept(false) |
C5041 | ‘definition’: out-of-line definition for constexpr static data member is not needed and is deprecated in C++17 |
C5042 | ‘declaration’: function declarations at block scope cannot be specified ‘inline’ in standard C++; remove ‘inline’ specifier |
C5043 | ‘specification’: exception specification does not match previous declaration |
Предупреждения, появившиеся в Visual Studio 2017 версии 15.3 (компилятор версии 19.11.25506.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.10 компилятора .
Предупреждение | Сообщение |
---|---|
C4597 | undefined behavior: description |
C4604 | ‘type’: passing argument by value across native and managed boundary requires valid copy constructor. Otherwise the runtime behavior is undefined |
C4749 | conditionally supported: description |
C4768 | __declspec attributes before linkage specification are ignored |
C4834 | discarding return value of function with ‘nodiscard’ attribute |
C4841 | non-standard extension used: extension |
C4842 | the result of ‘offsetof’ applied to a type using multiple inheritance is not guaranteed to be consistent between compiler releases |
C4869 | ‘nodiscard’ may only be applied to classes, enumerations, and functions with non-void return type |
C4984 | ‘if constexpr’ is a C++17 language extension |
C5033 | ‘*storage-class*’ is no longer a supported storage class |
C5034 | use of intrinsic ‘intrinsic’ causes function function to be compiled as guest code |
C5035 | use of feature ‘feature’ causes function function to be compiled as guest code |
C5036 | varargs function pointer conversion when compiling with /hybrid:x86arm64 ‘type1’ to ‘type2’ |
C5037 | ‘*member-function*’: an out-of-line definition of a member of a class template cannot have default arguments |
C5038 | data member ‘member1’ will be initialized after data member ‘member2’ |
Предупреждения, появившиеся в Visual Studio 2017 RTM (компилятор версии 19.10.25017.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.00 компилятора .
Предупреждение | Сообщение |
---|---|
C4468 | ‘fallthrough’: attribute must be followed by a case label or a default label |
C4698 | ‘feature’ is for evaluation purposes only and is subject to change or removal in future updates. |
C4839 | non-standard use of class ‘class’ as an argument to a variadic function |
C4840 | non-portable use of class ‘class’ as an argument to a variadic function |
Предупреждения, появившиеся в Visual Studio 2015 с обновлением 3 (компилятор версии 19.00.24215.1)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.00.23918 компилятора .
Предупреждение | Сообщение |
---|---|
C4467 | usage of ATL attributes is deprecated |
C4596 | ‘name’: illegal qualified name in member declaration |
C4598 | ‘#include ‘: header number number in the source does not match source at that position |
C4599 | ‘argument’: source argument number number does not match source |
Предупреждения, появившиеся в Visual Studio 2015 с обновлением 2 (компилятор версии 19.00.23918.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.00.23506 компилятора .
Предупреждение | Сообщение |
---|---|
C4466 | Could not perform coroutine heap elision |
C4595 | ‘class’: non-member operator new or delete functions may not be declared inline |
C4828 | The file contains a character starting at offset 0xvalue that is illegal in the current source character set (codepage number). |
C4868 | compiler may not enforce left-to-right evaluation order in braced initializer list |
Предупреждения, появившиеся в Visual Studio 2015 с обновлением 1 (компилятор версии 19.00.23506.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:19.00.23026 компилятора .
Предупреждение | Сообщение |
---|---|
C4426 | optimization flags changed after including header, may be due to #pragma optimize() |
C4654 | Code placed before include of precompiled header line will be ignored. Add code to precompiled header. |
C5031 | #pragma warning(pop): likely mismatch, popping warning state pushed in different file |
C5032 | detected #pragma warning(push) with no corresponding #pragma warning(pop) |
Предупреждения, появившиеся в Visual Studio 2015 RTM (компилятор версии 19.00.23026.0)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:18 компилятора .
Предупреждение | Сообщение |
---|---|
C4427 | ‘error’: overflow in constant division, undefined behavior |
C4438 | ‘type’: cannot be called safely in /await:clrcompat mode. If ‘type’ calls into the CLR it may result in CLR head corruption |
C4455 | ‘operator name’: literal suffix identifiers that do not start with an underscore are reserved |
C4456 | declaration of ‘name’ hides previous local declaration |
C4457 | declaration of ‘name’ hides function parameter |
C4458 | declaration of ‘name’ hides class member |
C4459 | declaration of ‘name’ hides global declaration |
C4462 | ‘type’ : cannot determine the GUID of the type. Program may fail at runtime. |
C4463 | overflow; assigning value to bit-field that can only hold values from value to value |
C4473 | ‘function’ : not enough arguments passed for format string |
C4474 | ‘function’ : too many arguments passed for format string |
C4475 | ‘function’ : length modifier ‘modifier’ cannot be used with type field character ‘character’ in format specifier |
C4476 | ‘function’ : unknown type field character ‘character’ in format specifier |
C4477 | ‘function’ : format string ‘string’ requires an argument of type ‘type’, but variadic argument number has type ‘type’ |
C4478 | ‘function’ : positional and non-positional placeholders cannot be mixed in the same format string |
C4494 | ‘type’ : Ignoring __declspec(allocator) because the function return type is not a pointer or reference |
C4495 | nonstandard extension ‘__super’ used: replace with explicit base class name |
C4496 | nonstandard extension ‘for each’ used: replace with ranged-for statement |
C4497 | nonstandard extension ‘sealed’ used: replace with ‘final’ |
C4498 | nonstandard extension used: ‘extension’ |
C4499 | ‘specialization’: an explicit specialization cannot have a storage class (ignored) |
C4576 | a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax |
C4577 | ‘noexcept’ used with no exception handling mode specified; termination on exception is not guaranteed. Specify /EHsc |
C4578 | ‘abs’: conversion from ‘type’ to ‘type’, possible loss of data (Did you mean to call ‘name’ or to #include ?) |
C4582 | ‘type’: constructor is not implicitly called |
C4583 | ‘type’: destructor is not implicitly called |
C4587 | ‘type’: behavior change: constructor is no longer implicitly called |
C4588 | ‘type’: behavior change: destructor is no longer implicitly called |
C4589 | Constructor of abstract class ‘type’ ignores initializer for virtual base class ‘type’ |
C4591 | ‘constexpr’ call-depth limit of number exceeded (/constexpr:depth ) |
C4592 | ‘type’: symbol will be dynamically initialized (implementation limitation) |
C4593 | ‘type’: ‘constexpr’ call evaluation step limit of value exceeded; use /constexpr:steps to increase the limit |
C4647 | behavior change: __is_pod(type) has different value in previous versions |
C4648 | standard attribute ‘carries_dependency’ is ignored |
C4649 | attributes are ignored in this context |
C4753 | Cannot find bounds for pointer; MPX intrinsic function ignored |
C4771 | Bounds must be created using a simple pointer; MPX intrinsic function ignored |
C4774 | ‘description’ : format string expected in argument number is not a string literal |
C4775 | nonstandard extension used in format string ‘string’ of function ‘function’ |
C4776 | ‘%character’ is not allowed in the format string of function ‘function’ |
C4777 | ‘description’ : format string ‘string’ requires an argument of type ‘type’, but variadic argument number has type ‘type’ |
C4778 | ‘description’ : unterminated format string ‘string’ |
C4838 | conversion from ‘type’ to ‘type’ requires a narrowing conversion |
C5022 | ‘type’: multiple move constructors specified |
C5023 | ‘type’: multiple move assignment operators specified |
C5024 | ‘declaration’: move constructor was implicitly defined as deleted |
C5025 | ‘declaration’: move assignment operator was implicitly defined as deleted |
C5026 | ‘type’: move constructor was implicitly defined as deleted |
C5027 | ‘type’: move assignment operator was implicitly defined as deleted |
C5028 | ‘name’: Alignment specified in prior declaration (number) not specified in definition |
C5029 | nonstandard extension used: alignment attributes in C++ apply to variables, data members and tag types only |
C5030 | attribute ‘attribute’ is not recognized |
Предупреждения, появившиеся в Visual Studio 2013 (версия компилятора 18.00.21005.1)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:17 компилятора .
Предупреждение | Сообщение |
---|---|
C4301 | ‘type’: overriding virtual function only differs from ‘declaration’ by const/volatile qualifier |
C4316 | ‘type’: object allocated on the heap may not be aligned number |
C4380 | ‘type’: A default constructor cannot be deprecated |
C4388 | ‘token’: signed/unsigned mismatch |
C4423 | ‘std::bad_alloc’: will be caught by class (‘type’) on line number |
C4424 | catch for ‘type’ preceded by ‘type’ on line number; unpredictable behavior may result if ‘std::bad_alloc’ is thrown |
C4425 | A SAL annotation cannot be applied to ‘. ‘ |
C4464 | relative include path contains ‘..’ |
C4575 | ‘__vectorcall’ incompatible with the ‘/clr’ option: converting to ‘__stdcall’ |
C4609 | ‘type’ derives from default interface ‘type’ on type ‘type’. Use a different default interface for ‘type’, or break the base/derived relationship. |
C4754 | Conversion rules for arithmetic operations in the comparison at description(number) mean that one branch cannot be executed. Cast ‘type’ to ‘type’ (or similar type of number bytes). |
C4755 | Conversion rules for arithmetic operations in the comparison at description(number) mean that one branch cannot be executed in an inlined function. Cast ‘type’ to ‘type’ (or similar type of number bytes). |
C4767 | section name ‘name’ is longer than 8 characters and will be truncated by the linker |
C4770 | partially validated enum ‘name’ used as index |
C4827 | A public ‘ToString’ method with 0 parameters should be marked as virtual and override |
C4882 | passing functors with non-const call operators to concurrency::parallel_for_each is deprecated |
C4973 | ‘type’: marked as deprecated |
C4974 | ‘type’: marked as deprecated |
C4981 | Warbird: function ‘declaration’ marked as __forceinline not inlined because it contains exception semantics |
C4990 | Warbird: message |
C4991 | Warbird: function ‘declaration’ marked as __forceinline not inlined because protection level of inlinee is greater than the parent |
C4992 | Warbird: function ‘declaration’ marked as __forceinline not inlined because it contains inline assembly which cannot be protected |
Предупреждения, появившиеся в Visual Studio 2012 (версия компилятора 17.00.51106.1)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:16 компилятора .
Предупреждение | Сообщение |
---|---|
C4330 | attribute ‘attribute’ for section ‘section’ ignored |
C4415 | duplicate __declspec(code_seg(‘name’)) |
C4416 | __declspec(code_seg(. )) contains empty string: ignored |
C4417 | an explicit template instantiation cannot have __declspec(code_seg(. )): ignored |
C4418 | __declspec(code_seg(. )) ignored on an enum |
C4419 | ‘name’ has no effect when applied to private ref class ‘type’. |
C4435 | ‘type’: Object layout under /vd2 will change due to virtual base ‘type’ |
C4436 | dynamic_cast from virtual base ‘type’ to ‘type’ in constructor or destructor could fail with partially-constructed object |
C4437 | dynamic_cast from virtual base ‘type’ to ‘type’ could fail in some contexts |
C4443 | expected pragma parameter to be ‘0’, ‘1’, or ‘2’ |
C4446 | ‘type’: cannot map member ‘name’ into this type, due to conflict with the type name. The method was renamed to ‘name’ |
C4447 | ‘main’ signature found without threading model. Consider using ‘int main(Platform::Array
^ args)’. |
C4448 | ‘type’ does not have a default interface specified in metadata. Picking: ‘type’, which may fail at runtime. |
C4449 | ‘type’ an unsealed type should be marked as ‘[WebHostHidden]’ |
C4450 | ‘type’ should be marked as ‘[WebHostHidden]’ because it derives from ‘type’ |
C4451 | ‘type’: Usage of ref class ‘type’ inside this context can lead to invalid marshaling of object across contexts |
C4452 | ‘type’: public type cannot be at global scope. It must be in a namespace that is a child of the name of the output .winmd file. |
C4453 | ‘type’: A ‘[WebHostHidden]’ type should not be used on the published surface of a public type that is not ‘[WebHostHidden]’ |
C4454 | ‘type’ is overloaded by more than the number of input parameters without having [DefaultOverload] specified. Picking ‘declaration’ as the default overload |
C4471 | ‘name’: a forward declaration of an unscoped enumeration must have an underlying type (int assumed) |
C4472 | ‘name’ is a native enum: add an access specifier (private/public) to declare a managed/WinRT enum |
C4492 | ‘type’: matches base ref class method ‘type’, but is not marked ‘override’ |
C4493 | delete expression has no effect as the destructor of ‘type’ does not have ‘public’ accessibility |
C4585 | ‘type’: A WinRT ‘public ref class’ must either be sealed or derive from an existing unsealed class |
C4586 | ‘type’: A public type cannot be declared in a top-level namespace called ‘Windows’ |
C4695 | #pragma execution_character_set: ‘argument’ is not a supported argument: currently only ‘UTF-8’ is supported |
C4703 | potentially uninitialized local pointer variable ‘name’ used |
C4728 | /Yl- option ignored because PCH reference is required |
C4745 | volatile access of ‘name’ cannot be honored due to its size |
C4746 | volatile access of ‘name’ is subject to /volatile: setting; consider using __iso_volatile_load/store intrinsic functions |
C4872 | floating point division by zero detected when compiling the call graph for the concurrency::parallel_for_each at: ‘description’ |
C4880 | casting from ‘type’ to ‘type’: casting away constness from a pointer or reference may result in undefined behavior in an amp restricted function |
C4881 | the constructor and/or the destructor will not be invoked for tile_static variable ‘type’ |
C4966 | ‘description’ has __code_seg annotation with unsupported segment name, annotation ignored |
C4988 | ‘type’: variable declared outside class/function scope |
C4989 | ‘description’: type has conflicting definitions. |
Предупреждения, появившиеся в Visual Studio 2010 (версия компилятора 16.00.40219.01)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:15 компилятора .
Предупреждение | Сообщение |
---|---|
C4352 | ‘name’: intrinsic function already defined |
C4573 | the usage of ‘type’ requires the compiler to capture ‘this’ but the current default capture mode does not allow it |
C4574 | ‘name’ is defined to be ‘0’: did you mean to use ‘#if name’? |
C4689 | ‘character’: unsupported character in #pragma detect_mismatch; #pragma ignored |
C4751 | /arch AVX flag does not apply to Intel(R) Streaming SIMD Extensions that are within inline ASM |
C4752 | found Intel(R) Advanced Vector Extensions; consider using the appropriate /arch AVX flag |
C4837 | trigraph detected: ‘??character’ replaced by ‘character’ |
C4986 | ‘declaration’: exception specification does not match previous declaration |
C4987 | nonstandard extension used: ‘throw (. )’ |
Предупреждения, появившиеся в Visual Studio 2008 (версия компилятора 15.00.21022.08)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:14 компилятора .
Предупреждение | Сообщение |
---|---|
C4396 | ‘type’: the inline specifier cannot be used when a friend declaration refers to a specialization of a function template |
C4413 | ‘declaration’: reference member is initialized to a temporary that doesn’t persist after the constructor exits |
C4491 | ‘description’: has an illegal IDL version format |
C4603 | ‘name’: macro is not defined or definition is different after precompiled header use |
C4627 | ‘description’: skipped when looking for precompiled header use |
C4750 | ‘description’: function with _alloca() inlined into a loop |
C4910 | ‘type’: ‘__declspec(dllexport)’ and ‘extern’ are incompatible on an explicit instantiation |
C4985 | ‘declaration’: attributes not present on previous declaration. |
Предупреждения, появившиеся в Visual Studio 2005 (версия компилятора 14.00.50727.762)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:13 компилятора .
Предупреждение | Сообщение |
---|---|
C4000 | UNKNOWN WARNING Please choose the Technical Support command on the Visual C++ Help menu, or open the Technical Support help file for more information |
C4272 | ‘type’: is marked __declspec(dllimport); must specify native calling convention when importing a function. |
C4333 | ‘expression’: right shift by too large amount, data loss |
C4334 | ‘expression’: result of 32-bit shift implicitly converted to 64 bits (was 64-bit shift intended?) |
C4335 | Mac file format detected: please convert the source file to either DOS or UNIX format |
C4342 | behavior change: ‘type’ called, but a member operator was called in previous versions |
C4350 | behavior change: ‘declaration’ called instead of ‘declaration’ |
C4357 | param array argument found in formal argument list for delegate ‘declaration’ ignored when generating ‘type’ |
C4358 | ‘expression’: return type of combined delegates is not ‘void’; returned value is undefined |
C4359 | ‘type’: Alignment specifier is less than actual alignment (number), and will be ignored. |
C4362 | ‘type’: alignment greater than 8 bytes is not supported by CLR |
C4364 | #using for assembly ‘name’ previously seen at description(number) without as_friend attribute; as_friend not applied |
C4365 | ‘expression’: conversion from ‘type’ to ‘type’, signed/unsigned mismatch |
C4366 | The result of the unary ‘operator’ operator may be unaligned |
C4367 | Conversion from ‘type’ to ‘type’ may cause datatype misalignment exception |
C4368 | cannot define ‘name’ as a member of managed ‘type’: mixed types are not supported |
C4369 | ‘type’: enumerator value ‘number’ cannot be represented as ‘type’, value is ‘number’ |
C4374 | ‘declaration’: interface method will not be implemented by non-virtual method ‘declaration’ |
C4375 | non-public method ‘declaration’ does not override ‘declaration’ |
C4376 | access specifier ‘specifier:’ is no longer supported: please use ‘specifier:’ instead |
C4377 | native types are private by default; -d1PrivateNativeTypes is deprecated |
C4378 | Must obtain function pointers to run initializers; consider System::ModuleHandle::ResolveMethodHandle |
C4379 | Version version of the common language runtime is not supported by this compiler. Using this version may cause unexpected results |
C4381 | ‘declaration’: interface method will not be implemented by non-public method ‘declaration’ |
C4382 | throwing ‘type’: a type with __clrcall destructor or copy constructor can only be caught in /clr:pure module |
C4383 | ‘type’: the meaning of dereferencing a handle can change, when a user-defined ‘operator’ operator exists; write the operator as a static function to be explicit about the operand |
C4384 | #pragma ‘directive’ should only be used at global scope |
C4393 | ‘type’: const has no effect on description data member; ignored |
C4394 | ‘type’: per-appdomain symbol should not be marked with __declspec(value) |
C4395 | ‘type’: member function will be invoked on a copy of the initonly data member ‘type’ |
C4397 | DefaultCharSetAttribute is ignored |
C4398 | ‘type’: per-process global object might not work correctly with multiple appdomains; consider using __declspec(appdomain) |
C4399 | ‘type’: per-process symbol should not be marked with __declspec(value) when compiled with /clr:pure |
C4400 | ‘type’: const/volatile qualifiers on this type are not supported |
C4412 | ‘declaration’: function signature contains type ‘type’; C++ objects are unsafe to pass between pure code and mixed or native. |
C4429 | possible incomplete or improperly formed universal-character-name |
C4430 | missing type specifier — int assumed. Note: C++ does not support default-int |
C4431 | missing type specifier — int assumed. Note: C no longer supports default-int |
C4434 | a static constructor must have private accessibility; changing to private access |
C4439 | ‘type’: function definition with a managed type in the signature must have a __clrcall calling convention |
C4441 | calling convention of ‘convention’ ignored; ‘convention’ used instead |
C4445 | ‘declaration’: in a managed/WinRT type a virtual method cannot be private |
C4460 | CLR/WinRT operator ‘type’, has parameter passed by reference. CLR/WinRT operator ‘operator’ has different semantics from C++ operator ‘operator’, did you intend to pass by value? |
C4461 | ‘type’: this class has a finalizer ‘!type’ but no destructor ‘
type’ |
C4470 | floating-point control pragmas ignored under /clr |
C4480 | nonstandard extension used: specifying underlying type for enum ‘type’ |
C4481 | nonstandard extension used: override specifier ‘specifier’ |
C4482 | nonstandard extension used: enum ‘type’ used in qualified name |
C4483 | syntax error: expected C++ keyword |
C4484 | ‘type’: matches base ref class method ‘type’, but is not marked ‘virtual’, ‘new’ or ‘override’; ‘new’ (and not ‘virtual’) is assumed |
C4485 | ‘type’: matches base ref class method ‘type’, but is not marked ‘new’ or ‘override’; ‘new’ (and ‘virtual’) is assumed |
C4486 | ‘type’: a private virtual method of a ref class or value class should be marked ‘sealed’ |
C4487 | ‘type’: matches inherited non-virtual method ‘type’ but is not explicitly marked ‘new’ |
C4488 | ‘type’: requires ‘keyword’ keyword to implement the interface method ‘type’ |
C4489 | ‘keyword’: not allowed on interface method ‘name’; override specifiers are only allowed on ref class and value class methods |
C4490 | ‘keyword’: incorrect use of override specifier; ‘type’ does not match a base ref class method |
C4538 | ‘type’: const/volatile qualifiers on this type are not supported |
C4559 | ‘type’: redefinition; the function gains __declspec(value) |
C4565 | ‘type’: redefinition; the symbol was previously declared with __declspec(value) |
C4566 | character represented by universal-character-name ‘character’ cannot be represented in the current code page (number) |
C4568 | ‘type’: no members match the signature of the explicit override |
C4569 | ‘type’: no members match the signature of the explicit override |
C4570 | ‘type’: is not explicitly declared as abstract but has abstract functions |
C4571 | Informational: catch(. ) semantics changed since Visual C++ 7.1; structured exceptions (SEH) are no longer caught |
C4572 | [ParamArray] attribute is deprecated under /clr, use ‘. ‘ instead |
C4580 | [attribute] is deprecated; instead specify specifiedAttribute as a base class |
C4581 | deprecated behavior: ‘»name»‘ replaced with ‘name’ to process attribute |
C4606 | #pragma warning: ‘number’ ignored; Code Analysis warnings are not associated with warning levels |
C4631 | MSXML or XPath unavailable, XML document comments will not be processed. description |
C4632 | XML document comment: description — access denied: description |
C4633 | XML document comment description: error: description |
C4634 | XML document comment description: cannot be applied: description |
C4635 | XML document comment description: badly-formed XML: description |
C4636 | XML document comment description: tag requires non-empty ‘description’ attribute. |
C4637 | XML document comment description: tag discarded. description |
C4638 | XML document comment description: reference to unknown symbol ‘description’. |
C4639 | MSXML error, XML document comments will not be processed. description |
C4641 | XML document comment has an ambiguous cross reference: |
C4678 | base class ‘declaration’ is less accessible than ‘name’ |
C4679 | ‘description’: could not import member |
C4687 | ‘type’: a sealed abstract class cannot implement an interface ‘type’ |
C4688 | ‘name’: constraint list contains assembly private type ‘declaration’ |
C4690 | [ emitidl( pop ) ]: more pops than pushes |
C4691 | ‘type’: type referenced was expected in unreferenced module ‘description’, type defined in current translation unit used instead |
C4692 | ‘name’: signature of non-private member contains assembly private native type ‘declaration’ |
C4693 | ‘type’: a sealed abstract class cannot have any instance members ‘name’ |
C4694 | ‘type’: a sealed abstract class cannot have a base-class ‘type’ |
C4720 | in-line assembler reports: ‘description’ |
C4721 | ‘description’: not available as an intrinsic |
C4722 | ‘description’: destructor never returns, potential memory leak |
C4726 | ARM arch4/4T supports only ‘ or ‘ with immediate value |
C4727 | PCH named name with same timestamp found in name and name. Using first PCH. |
C4729 | function too big for flow graph based warnings |
C4730 | ‘description’: mixing _m64 and floating point expressions may result in incorrect code |
C4731 | ‘description’: frame pointer register ‘register’ modified by inline assembly code |
C4732 | intrinsic ‘intrinsic’ is not supported in this architecture |
C4733 | Inline asm assigning to ‘FS:0’: handler not registered as safe handler |
C4734 | More than 64k line numbers in a COFF debug info section; stop emitting COFF debug line numbers for module ‘module’ |
C4738 | storing 32-bit float result in memory, possible loss of performance |
C4739 | reference to variable ‘variable’ exceeds its storage space |
C4740 | flow in or out of inline asm code suppresses global optimization |
C4742 | ‘variable’ has different alignment in ‘location’ and ‘location’: number and number |
C4743 | ‘name’ has different size in ‘location’ and ‘location’: number and number bytes |
C4744 | ‘name’ has different type in ‘location’ and ‘location’: ‘type’ and ‘type’ |
C4747 | Calling managed ‘type’: Managed code may not be run under loader lock, including the DLL entrypoint and calls reached from the DLL entrypoint |
C4761 | integral size mismatch in argument; conversion supplied |
C4764 | Cannot align catch objects to greater than 16 bytes |
C4788 | ‘identifier’: identifier was truncated to ‘number’ characters |
C4789 | buffer ‘name’ of size number bytes will be overrun; number bytes will be written starting at offset number |
C4801 | Return by reference is not verifiable: description |
C4819 | The file contains a character that cannot be represented in the current code page (number). Save the file in Unicode format to prevent data loss |
C4826 | Conversion from ‘type’ to ‘type’ is sign-extended. This may cause unexpected runtime behavior. |
C4829 | Possibly incorrect parameters to function main. Consider ‘int main(Platform::Array
^ argv)’ |
C4835 | ‘type’: the initializer for exported data will not be run until managed code is first executed in the host assembly |
C4867 | ‘type’: non-standard syntax; use ‘&’ to create a pointer to member |
C4936 | this __declspec is supported only when compiled with /clr or /clr:pure |
C4937 | ‘name’ and ‘name’ are indistinguishable as arguments to ‘option’ |
C4938 | ‘type’: Floating point reduction variable may cause inconsistent results under /fp:strict or #pragma fenv_access |
C4939 | #pragma vtordisp is deprecated and will be removed in a future release of Visual C++ |
C4947 | ‘type’: marked as obsolete |
C4949 | pragmas ‘managed’ and ‘unmanaged’ are meaningful only when compiled with ‘/clr[:option]’ |
C4950 | ‘type’: marked as obsolete |
C4955 | ‘description’: import ignored; already imported from ‘source’ |
C4956 | ‘type’: this type is not verifiable |
C4957 | ‘expression’: explicit cast from ‘type’ to ‘type’ is not verifiable |
C4958 | ‘expression’: pointer arithmetic is not verifiable |
C4959 | cannot define unmanaged class ‘type’ in /clr:safe because accessing its members yields unverifiable code |
C4960 | ‘description’ is too big to be profiled |
C4961 | No profile data was merged into ‘location’, profile-guided optimizations disabled |
C4962 | ‘description’: Profile-guided optimizations disabled because optimizations caused profile data to become inconsistent |
C4963 | ‘description’: no profile data found; different compiler options were used in instrumented build |
C4964 | No optimization options were specified; profile info will not be collected |
C4965 | implicit box of integer 0; use nullptr or explicit cast |
C4970 | delegate constructor: target object ignored since ‘declaration’ is static |
C4971 | Argument order: , for delegate constructor is deprecated, use , |
C4972 | Directly modifying or treating the result of an unbox operation as an lvalue is unverifiable |
Предупреждения, появившиеся в Visual Studio 2003 (версия компилятора 13.10.3077)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:13.00.9466 компилятора .
Предупреждение | Сообщение |
---|---|
C4343 | #pragma optimize(description,off) overrides /Og option |
C4344 | behavior change: use of explicit template arguments results in call to ‘declaration’ |
C4346 | ‘type’: dependent name is not a type |
C4348 | ‘declaration’: redefinition of default parameter: parameter number |
C4356 | ‘type’: static data member cannot be initialized via derived class |
C4408 | anonymous struct did not declare any data members |
C4544 | ‘declaration’: default template argument ignored on this template declaration |
C4545 | expression before comma evaluates to a function which is missing an argument list |
C4546 | function call before comma missing argument list |
C4547 | ‘expression’: operator before comma has no effect; expected operator with side-effect |
C4548 | expression before comma has no effect; expected expression with side-effect |
C4549 | ‘expression’: operator before comma has no effect; did you intend ‘expression’? |
C4628 | digraphs not supported with -Ze. Character sequence ‘sequence’ not interpreted as alternate token for ‘token’ |
C4629 | digraph used, character sequence ‘sequence’ interpreted as token ‘token’ (insert a space between the two characters if this is not what you intended) |
C4671 | ‘description’: the copy constructor is inaccessible |
C4676 | ‘description’: the destructor is inaccessible |
C4677 | ‘name’: signature of non-private member contains assembly private type ‘declaration’ |
C4686 | ‘type’: possible change in behavior, change in UDT return calling convention |
C4812 | obsolete declaration style: please use ‘type::name’ instead |
C4813 | ‘type’: a friend function of a local class must have been previously declared |
C4821 | Unable to determine Unicode encoding type, please save the file with signature (BOM) |
C4822 | ‘type’: local class member function does not have a body |
C4823 | ‘type’: uses pinning pointers but unwind semantics are not enabled. Consider using /EHa |
C4913 | user defined binary operator ‘,’ exists but no overload could convert all operands, default built-in binary operator ‘,’ used |
C4948 | return type of ‘declaration’ does not match the last parameter type of the corresponding setter |
C4951 | ‘description’ has been edited since profile data was collected, function profile data not used |
C4952 | ‘description’: no profile data found in program database ‘description’ |
C4953 | Inlinee ‘description’ has been edited since profile data was collected, profile data not used |
C4954 | ‘description’: not profiled (contains __int64 switch expression) |
Предупреждения, появившиеся в Visual Studio 2002 (версия компилятора 13.00.9466)
Эти предупреждения и все предупреждения в более поздних версиях подавляются с помощью параметра /Wv:12 компилятора .
Источник
Error statement with no effect
cant figure out how to fix this error. here is the error code i get:
line col
11 9 [Error] statement has no effect [-Werror=unused-value]
11 9 [Error] statement is a reference, not call, to function ‘ifPrime’ [-Werror=address]
12 6 [Error] unused variable ‘value’ [-Werror=unused-variable]
help is greatly appreciated.
here is the numbers for the numbersinput file:
This program seems like a good chance to use a loop. A for loop has the following syntax:
Your conditionals for the ifPrime() function are also off.
Here is a link that will explain these things better than I can:
http://www.cplusplus.com/doc/tutorial/control/
Below is a restructured version of your program, although the ifPrime() function is still not correct:
You’re on the right track for the ifPrime function. I would use the modulus operator (%) which will return the remainder of division. EX: 15 % 2 = 1, since 15 / 2 has one as a remainder. Using that and a loop, iterate through values less than the value1 and break if value1 % loopCount equals 0. Additionally, why are there 3 values being passed to ifPrime? It only uses one of them.
In this situation, there is no need to store all the values from the file, not in an array, nor in many separate variables.
Just read a single value from the file, test whether or not it is prime, write it to the output file only if it is prime. Repeat.
Function ifprime should have a return type of bool and take a single parameter, the number being tested. Return true in the case of a prime number, otherwise return false.
bool ifPrime( int );
11 9 [Error] statement has no effect [-Werror=unused-value]
The statement ifPrime; does not call ifPrime, it just returns the function’s address, which is then thrown away. So the
on the program.
11 9 [Error] statement is a reference, not call, to function ‘ifPrime’ [-Werror=address]
Like I said, that statement doesn’t call function ifPrime.
12 6 [Error] unused variable ‘value’ [-Werror=unused-variable]
At line 13 you declare variable «value», but you never use it in the program.
One other bug: function names in C++ are case sensitive, so the function ifPrime() that you declare at line 6 is NOT the same as the function IfPrime that you call define at line 179
> this is for a project where they want us to test 50 numbers from an input file
> test them to see if they are prime and then if they are prime to put them in an output file.
Chervil +1
>> there is no need to store all the values from the file, not in an array, nor in many separate variables.
>> Just read a single value from the file, test whether or not it is prime,
>> write it to the output file only if it is prime. Repeat.
Источник
Исследование одного неопределённого поведения
В статье исследуются возможные проявления неопределённого поведения, возникающего в c++ при завершении не-void функции без вызова return с подходящим значением. Статья носит больше научно-развлекательный характер, чем практический.
Кому не нравится весело скакать по граблям — проходим мимо, не задерживаемся.
Введение
Всем известно, что при разработке c++-кода следует не допускать неопределённого поведения.
Однако:
- неопределённое поведение может казаться не достаточно опасным из-за абстрактности возможных последствий;
- не всегда понятно, где грань.
Попробуем конкретизировать возможные проявления неопределённого поведения, возникающего в одном довольно простом случае — в не-void функции отсутствует return.
Для этого рассмотрим код, генерируемый наиболее популярными компиляторами в разных режимах оптимизации.
Исследования под Linux будут проводиться с помощью Compiler Explorer. Исследования под Windows и macOs X — на непосредственно доступном мне железе.
Все сборки будут делаться для x86-x64.
Никаких мер для усиления либо подавления предупреждений/ошибок компиляторов предприниматься не будет.
Будет много дизассемблированного кода. Его оформление, к сожалению, разношёрстное, т.к. приходится использовать несколько разных инструментов (хорошо хоть удалось добиться везде синтаксиса Intel). К дизассемблированному коду я буду давать в меру подробные комментарии, которые, однако, не избавляют от необходимости знания регистров процессора и принципов работы стека.
Читаем Стандарт
6.6.3 The return statement
…
Flowing off the end of a function is equivalent to a return with no value; this results in undefined
behavior in a value-returning function.
…
Достижение конца функции эквивалентно выражению return без возвращаемого значения; для функции, у которой возвращаемое значение предусмотрено, это приводит к неопределённому поведению.
9.6.3 The return statement
…
Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main (6.8.3.1) results in undefined behavior.
…
Достижение конца конструктора, деструктора или функции с возвращаемым значением void (возможно, с квалификаторами const и volatile) эквивалентно выражению return без возвращаемого значения. Для всех других функций это приводит к неопределённому поведению (кроме функции main).
Что это значит на практике?
Если сигнатура функции предусматривает возвращаемое значение:
- её выполнение должно завершаться выражением return с экземпляром подходящего типа;
- иначе — неопределённое поведение;
- неопределённое поведение начинается не с момента вызова такой функции и не с момента использования возвращённого значение, а с момента ненадлежащего завершения такой функции;
- если функция содержит как корректные, так и некорректные пути выполнения — неопределённое поведение будет возникать только на некорректных путях;
- рассматриваемое неопределённое поведение не затрагивает выполнение инструкций, содержащихся в теле функции.
Фраза про функцию main не является новшеством c++17 — в предыдущих версиях Стандарта аналогичное исключение было описано в разделе 3.6.1 Main function.
Пример 1 — bool
В c++ нет ни одного типа с состоянием более простым, чем bool. Вот с него и начнём.
MSVC выдаёт на такой пример ошибку компиляции C4716, поэтому для MSVC код придётся слегка усложнить, предоставив хотя бы один корректный путь выполнения:
Платформа | Компилятор | Результат компиляции |
---|---|---|
Linux | x86-x64 Clang 10.0.0 | warning: non-void function does not return a value [-Wreturn-type] |
Linux | x86-x64 gcc 9.3 | warning: no return statement in function returning non-void [-Wreturn-type] |
macOs X | Apple clang version 11.0.0 | warning: control reaches end of non-void function [-Wreturn-type] |
Windows | MSVC 2019 16.5.4 | Оригинальный пример — error C4716, усложнённый — warning C4715: not all control paths return a value |
Оптимизация | Program return | Console output |
Linux x86-x64 Clang 10.0.0 | ||
-O0 | 255 | No output |
-O1, -O2 | No output | |
Linux x86-x64 gcc 9.3 | ||
-O0 | 89 | |
-O1, -O2, -O3 | No output | |
macOs X Apple clang version 11.0.0 | ||
-O0, -O1, -O2 | ||
Windows MSVC 2019 16.5.4, оригинальный пример | ||
/Od, /O1, /O2 | No build | No build |
Windows MSVC 2019 16.5.4, усложнённый пример | ||
/Od | 41 | |
/O1, /O2 | 1 |
Даже в этом простейшем примере четыре компилятора продемонстрировали как минимум три варианта проявления неопределённого поведения.
Идём разбираться, что же там эти компиляторы накомпилировали.
Linux x86-x64 Clang 10.0.0, -O0
Последняя инструкция в функции bad() — ud2.
Описание инструкции из Intel 64 and IA-32 Architectures Software Developer’s Manual:
UD2—Undefined Instruction
Generates an invalid opcode exception. This instruction is provided for software testing to explicitly generate an invalid opcode exception. The opcode for this instruction is reserved for this purpose.
Other than raising the invalid opcode exception, this instruction has no effect on processor state or memory.
Even though it is the execution of the UD2 instruction that causes the invalid opcode exception, the instruction pointer saved by delivery of the exception references the UD2 instruction (and not the following instruction).
This instruction’s operation is the same in non-64-bit modes and 64-bit mode.
Если кратко — это специальная инструкция для генерации исключения.
Надо обернуть вызов bad() в блок try… catch !?
Как бы не так. Это не c++-исключение.
Можно ли отловить ud2 в рантайме?
Под Windows для этого следует использовать __try, под Linux и macOs X — обработчик сигнала SIGILL.
Linux x86-x64 Clang 10.0.0, -O1, -O2
В результате оптимизации компилятор просто взял и выбросил как тело функции bad(), так и её вызов.
Linux x86-x64 gcc 9.3, -O0
Пояснения (в обратном порядке, т.к. в данном случае цепочку проще разбирать с конца):
5. Вызывается оператор вывода в stream для bool (строка 14);
4. В регистр edi помещается адрес std::cout — это первый аргумент оператора вывода в stream (строка 13);
3. В регистр esi помещается содержимое регистра eax — это второй аргумент оператора вывода в stream (строка 12);
2. Обнуляются три старших байта eax, значение al при этом не меняется (строка 11);
1. Вызывается функция bad() (строка 10);
0. Функция bad() должна поместить возвращаемое значение в регистр al.
Вместо этого в строке 4 — nop (No Operation, пустышка).
В консоль выводится один байт мусора из регистра al. Программа завершается штатно.
Linux x86-x64 gcc 9.3, -O1, -O2, -O3
Компилятор всё повыбрасывал в результате оптимизации.
macOs X Apple clang version 11.0.0, -O0
Путь булевского аргумента оператора вывода в поток (на сей раз в прямом порядке):
1. В регистр edx помещается содержимое регистра al (строка 8);
2. Зануляются все биты регистра edx, кроме младшего (строка 9);
3. В регистр rdi помещается указатель на std::cout — это первый аргумент оператора вывода в stream (строка 10);
4. В регистр esi помещается содержимое регистра edx — это второй аргумент оператора вывода в stream (строка 11);
5. Вызывается оператор вывода в stream для bool (строка 13);
Функция main ожидает получить результат выполнения функции bad() из регистра al.
1. В регистр al помещается значение из следующего, ещё не выделенного, байта стека (строка 4);
2. Зануляются все биты регистра al, кроме младшего (строка 5);
В консоль выводится один бит мусора из нераспределённого стека. Так получилось, что при тестовом запуске там оказался ноль.
Программа завершается штатно.
macOs X Apple clang version 11.0.0, -O1, -O2
Булевский аргумент оператора вывода в stream обнуляется (строка 5).
Вызов bad() выброшен при оптимизации.
Программа всегда выводит в консоль ноль и завершается штатно.
Windows MSVC 2019 16.5.4, усложнённый пример, /Od
Видно, что функция bad() должна предоставить возвращаемое значение в регистре al.
Значение, возвращённое функцией bad(), помещается сначала на стек, а потом в регистр edx для вывода в stream.
В консоль выводится один байт мусора из регистра al (если чуть точнее — то младший байт результата rand()). Программа завершается штатно.
Windows MSVC 2019 16.5.4, усложнённый пример, /O1, /O2
Компилятор принудительно заинлайнил вызов bad(). Функция main():
- копирует в ebx один байт из памяти, находящейся по адресу [rsp+30h];
- в случае, если rand() вернул ноль, копирует единицу из ecx в ebx (строка 11);
- копирует это же значение в dl (точнее, его младший байт) (строка 13);
- вызывает функцию вывода в stream, осуществляющую вывод значения dl (строка 14).
В stream выводится один байт мусора из оперативной памяти (из адреса rsp+30h).
Вывод по примеру 1
Оптимизация | Program return | Console output | Причина |
Linux x86-x64 Clang 10.0.0 | |||
-O0 | 255 | No output | ud2 |
-O1, -O2 | No output | Вывод в консоль и вызов функции bad() выброшены в результате оптимизации | |
Linux x86-x64 gcc 9.3 | |||
-O0 | 89 | Один байт мусора из регистра al | |
-O1, -O2, -O3 | No output | Вывод в консоль и вызов функции bad() выброшены в результате оптимизации | |
macOs X Apple clang version 11.0.0 | |||
-O0 | Один бит мусора из оперативной памяти | ||
-O1, -O2 | Вызов функции bad() заменён нулём | ||
Windows MSVC 2019 16.5.4, оригинальный пример | |||
/Od, /O1, /O2 | No build | No build | No build |
Windows MSVC 2019 16.5.4, усложнённый пример | |||
/Od | 41 | Один байт мусора из регистра al | |
/O1, /O2 | 1 | Один байт мусора из оперативной памяти |
Как оказалось, компиляторы продемонстрировали не 3, а целых 6 вариантов неопределённого поведения — просто до рассмотрения листингов дизассемблера мы не могли различить некоторые из них.
Пример 1a — управление неопределённым поведением
Попробуем немного порулить неопределённым поведением — повлиять на значение, возвращаемое функцией bad().
Это можно проделать только с теми компиляторами, которые выводят мусор.
Для этого надо подсовывать желаемые значения в те места, из которых компиляторы их будут брать.
Linux x86-x64 gcc 9.3, -O0
Пустая функция bad() не модифицирует значение регистра al, как от неё требует вызывающий код. Таким образом, если мы разместим в al определённое значение до вызова bad(), то ожидаем увидеть именно это значение в качестве результата выполнения bad().
Очевидно, что это можно сделать с помощью вызова любой другой функции, возвращающей bool. Но также это можно сделать с помощью функции, возвращающей, например, unsinged char.
Windows MSVC 2019 16.5.4, /Od
В примере для MSVC функция bad() возвращает младший байт результата rand().
Без модификации функции bad() внешний код может повлиять на возвращаемое ею значение, изменяя результат rand().
Windows MSVC 2019 16.5.4, /O1, /O2
macOs X Apple clang version 11.0.0, -O0
Надо перед вызовом bad() вписать определённое значение в ту ячейку памяти, которая будет на единицу младше вершины стека в момент вызова bad().
Пример предназначен для компиляции с опцией -O0, так что не стоит беспокоиться о сохранности переменной memory. Она не будет выброшена при оптимизации даже несмотря на то, что нигде не используется.
При этом переменная memory должна быть не просто единичным значением, а массивом — иначе компилятор располагает её в регистр процессора, а не на стек, как нам надо.
Пример не является универсальным, т.к. вообще компиляторы могут выделять на стеке больше памяти, чем необходимо для пользовательских переменных — тогда функция putToStack в текущем виде будет промахиваться.
Вроде получилось: удаётся менять выдачу функции bad(), и при этом учитывается только младший бит.
Вывод по примеру 1a
Пример позволил убедиться в корректности трактовки листингов дизассемблера.
Пример 1b — сломанный bool
Ну подууууумаешь, в консоль выведется «41» вместо «1»… Разве это опасно?
Проверять будем на двух компиляторах, предоставивших целый байт мусора.
Windows MSVC 2019 16.5.4, /Od
Неопределённое поведение привело к возникновению булевской переменной, которая ломает как минимум:
- операторы сравнения булевских значений;
- хеш-функцию булевского значения.
Windows MSVC 2019 16.5.4, /O1, /O2
badBool1: 213
badBool2: 137
if (badBool1): true
if (!badBool1): false
(badBool1 == true || badBool1 == false || badBool1 == badBool2): false
std::set .size(): 4
std::unordered_set .size(): 4
Работа с испорченной булевской переменной не изменилась при включении оптимизации.
Linux x86-x64 gcc 9.3, -O0
По сравнению с MSVC, в gcc добавилась ещё и некорректная работа оператора not.
Вывод по примеру 1b
Нарушение работы базовых операций с булевскими значениями может иметь серьёзные последствия для высокоуровневой логики.
Почему так произошло?
Потому что некоторые операции с булевскими переменными реализованы в предположении, что true — это строго единица.
В дизассемблере этот вопрос рассматривать не будем — статья и так получилась объёмной.
В очередной раз уточним таблицу с поведением компиляторов:
Оптимизация | Program return | Console output | Причина | Последствия использования результата bad() |
Linux x86-x64 Clang 10.0.0 | ||||
-O0 | 255 | No output | ud2 | |
-O1, -O2 | No output | Вывод в консоль и вызов функции bad() выброшены в результате оптимизации | ||
Linux x86-x64 gcc 9.3 | ||||
-O0 | 89 | Один байт мусора из регистра al | Нарушение работы: not; ==; !=; ; =; std::hash. |
|
-O1, -O2, -O3 | No output | Вывод в консоль и вызов функции bad() выброшены в результате оптимизации | ||
macOs X Apple clang version 11.0.0 | ||||
-O0 | Один бит мусора из оперативной памяти | |||
-O1, -O2 | Вызов функции bad() заменён нулём | |||
Windows MSVC 2019 16.5.4, оригинальный пример | ||||
/Od, /O1, /O2 | No build | No build | No build | |
Windows MSVC 2019 16.5.4, усложнённый пример | ||||
/Od | 41 | Один байт мусора из регистра al | Нарушение работы: ==; !=; ; =; std::hash. |
|
/O1, /O2 | 1 | Один байт мусора из оперативной памяти | Нарушение работы: ==; !=; ; =; std::hash. |
Четыре компилятора дали 7 различных проявлений неопределённого поведения.
Пример 2 — struct
Возьмём пример чуть посложнее:
Структура Test требует для конструирования один параметр типа int. Из её конструктора и деструктора производится вывод диагностических сообщений. Функция bad(int) имеет два корректных пути выполнения, ни один из которых не будет реализован при единственном вызове.
На этот раз — сначала таблица, потом разбор дизассемблера по непонятным пунктам.
Оптимизация | Program return | Console output | Причина |
Linux x86-x64 Clang 10.0.0 | |||
-O0 | 255 | rnd: 1804289383 | ud2 |
-O1, -O2 | rnd: 1804289383 Test::Test(142) 142 Test:: |
Test() Проверка if (v == 1) не производится. Блок else if превратился в просто else. Linux x86-x64 gcc 9.3 -O0 rnd: 1804289383
4198608
Test::
Test() nop вместо вызова конструктора на некорректном пути выполнения.
value содержит мусор из стека. -O1, -O2, -O3 rnd: 1804289383
Test::Test(142)
142
Test::
Test() Проверка if (v == 1) не производится. Блок else if превратился в просто else. macOs X Apple clang version 11.0.0 -O0 The program has unexpectedly finished. rnd: 16807 ud2 -O1, -O2 rnd: 16807
Test::Test(142)
142
Test::
Test() Проверка if (v == 1) не производится. Блок else if превратился в просто else. Windows MSVC 2019 16.5.4 /Od /RTCs Access violation reading location 0x00000000CCCCCCCC rnd: 41 Побочный эффект MSVC stack frame run-time error checking /Od, /O1, /O2 rnd: 41
8791061810776
Test::
Test() Мусор из ячейки памяти, адрес которой оказался в rax
Опять мы видим множество вариантов: кроме уже известного ud2 есть ещё как минимум 4 разных поведения.
Весьма интересно обращение компиляторов с конструктором:
- в одних случаях выполнение продолжилось без вызова конструктора — в этом случае объект оказался в каком-то случайном состоянии;
- в других случаях произошёл вызов конструктора, не предусмотренный на пути выполнения, что довольно странно.
Linux x86-x64 Clang 10.0.0, -O1, -O2
В коде производится только одно сравнение (строка 14), и присутствует только один условный переход (строка 15). Компилятор проигнорировал второе сравнение и второй условный переход.
Это наводит на подозрение, что неопределённое поведение началось раньше, чем предписывает Стандарт.
Но проверка условия второго if не содержит побочных эффектов, и логика компилятора сработала следующим образом:
- если второе условие окажется верным — надо вызвать конструктор Test с аргументом 142;
- если второе условие окажется не верным — произойдёт выход из функции без возрата значения, что означает неопределённое поведение, при котором компилятор может сделать всё, что угодно. В том числе — вызвать тот же конструктор с тем же аргументом;
- проверка является лишней, вызов конструктора Test с аргументом 142 можно производить без проверки условия.
Посмотрим, что произойдёт, если вторая проверка будет содержать условие с побочными эффектами:
Компилятор честно воспроизвёл все положенные побочные эффекты, вызвав rand() (строка 16), чем развеял сомнения о неподобающе раннем начале неопределённого поведения.
Windows MSVC 2019 16.5.4, /Od /RTCs
Опция /RTCs включает stack frame run-time error checking. Эта опция доступна только в debug-сборке. Рассмотрим дизассемблированный код участка main():
Перед вызовом bad(int) (строка 4) производится подготовка аргументов — в регистр edx копируется значение переменной rnd (строка 2), и в регистр rcx загружается эффективный адрес какой-то локальной переменной, расположенной по адресу rsp+28h (строка 3).
Предположительно, rsp+28 — адрес временной переменной, хранящей результат вызова bad(int).
Это предположение подтверждается строками 19 и 20 — эффективный адрес этой же переменной загружается в rcx, после чего вызывается деструктор.
Однако в интервале строк 4 — 18 к этой переменной нет обращения, несмотря на вывод в stream значения её поля данных.
Как мы видели из прошлых листингов MSVC, аргумент для оператора вывода в поток следует ожидать в регистре rdx. В регистр rdx попадает результат разыменования адреса, находящегося в rax (строка 9).
Таким образом, вызывающий код ожидает от bad(int):
- заполнения переменной, адрес которой передан через регистр rcx (тут мы видим RVO в действии);
- возврат адреса этой переменной через регистр rax.
Переходим к рассмотрению листинга bad(int):
- в eax заносится значение 0xCCCCCCCC, которое мы видели в сообщении Access violation (строка 9) (обратите внимание — только 4 байта, в то время как в сообщении AccessViolation адрес состоит из 8 байт);
- вызывается команда rep stos, осуществляющая 0xC циклов записи содержимого eax в память начиная с адреса rdi (строка 10). Это 48 байтов — ровно столько, сколько выделено на стеке в строке 6;
- на корректных путях выполнения в rax заносится значение из rsp+40h (строки 23, 36);
- значение регистра rcx (через который main() передал адрес назначения) помещается на стек по адресу rsp+8 (строка 4);
- в стек впихивается rdi, что приводит к уменьшению rsp на 8 (строка 5);
- на стеке выделяется 30h байт путём уменьшению rsp (строка 6).
Таким образом, rsp+8 в строке 4 и rsp+40h в остальной части кода — одно и то же значение.
Код довольно запутанный, т.к. в нём не применяется rbp.
В сообщении Access Violation есть целых две случайности:
- нули в старшей части адреса — там мог быть любой мусор;
- адрес случайно оказался некорректным.
Судя по всему, опция /RTCs включила затирание стека определёнными ненулевыми значениями, а сообщение Access Violation — лишь случайный побочный эффект.
Посмотрим, чем отличается код со включённой опцией /RTCs от кода без неё.
Код участков main() отличается только адресами локальных переменных на стеке.
(для наглядности я разместил рядом два варианта функции bad(int) — с /RTCs и без)
Без /RTCs исчезла инструкция rep stos и подготовка аргументов для неё в начале функции.
Пример 2a
Снова попробуем поуправлять неопределённым поведением. На этот раз только для одного компилятора.
Windows MSVC 2019 16.5.4, /Od /RTCs
С опцией /RTCs компилятор вставляет в начало функции bad(int) код, заполняющий младшую половину rax фиксированным значеним, что может приводить к Access violation.
Чтобы изменить это поведение, достаточно заполнить rax каким-либо корректным адресом.
Этого можно добиться очень простой модификацией: добавить в тело bad(int) вывод чего-нибудь в std::cout.
Источник
Code that has no effect or is never executed (that is, dead or unreachable code) is typically the result of a coding error and can cause unexpected behavior. Such code is usually optimized out of a program during compilation. However, to improve readability and ensure that logic errors are resolved, it should be identified, understood, and eliminated.
Statements or expressions that have no effect should be identified and removed from code. Most modern compilers, in many cases, can warn about code that has no effect or is never executed. (See MSC00-C. Compile cleanly at high warning levels.)
Noncompliant Code Example
This noncompliant code example demonstrates how dead code can be introduced into a program [Fortify 2006]. The second conditional statement, if (s)
, will never evaluate true because it requires that s
not be assigned NULL
, and the only path where s
can be assigned a non-null value ends with a return
statement.
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle Error */ } /* Process s */ return 0; } /* Code that doesn't touch s */ if (s) { /* This code is unreachable */ } return 0; }
Compliant Solution
Remediation of dead code requires the programmer to determine why the code is never executed and then to resolve the situation appropriately. To correct the preceding noncompliant code, the return
is removed from the body of the first conditional statement.
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle error */ } /* Process s */ } /* Code that doesn't touch s */ if (s) { /* This code is now reachable */ } return 0; }
Noncompliant Code Example
In this example, the strlen()
function is used to limit the number of times the function s_loop()
will iterate. The conditional statement inside the loop evaluates to true when the current character in the string is the null terminator. However, because strlen()
returns the number of characters that precede the null terminator, the conditional statement never evaluates true.
int s_loop(char *s) { size_t i; size_t len = strlen(s); for (i=0; i < len; i++) { /* Code that doesn't change s, i, or len */ if (s[i] == '') { /* This code is never reached */ } } return 0; }
Compliant Solution
Removing the dead code depends on the intent of the programmer. Assuming the intent is to flag and process the last character before the null terminator, the conditional is adjusted to correctly determine if the i
refers to the index of the last character before the null terminator.
int s_loop(char *s) { size_t i; size_t len = strlen(s); for (i=0; i < len; i++) { /* Code that doesn't change s, i, or len */ if (s[i+1] == '') { /* This code is now reached */ } } return 0; }
Noncompliant Code Example (Assignment)
In this noncompliant code example, the comparison of a
to b
has no effect:
int a; int b; /* ... */ a == b;
This code is likely a case of the programmer mistakenly using the equals operator ==
instead of the assignment operator =
.
Compliant Solution (Assignment)
The assignment of b
to a
is now properly performed:
int a; int b; /* ... */ a = b;
Noncompliant Code Example (Dereference)
In this example, a pointer increment and then a dereference occur, but the dereference has no effect:
Compliant Solution (Dereference)
Correcting this example depends on the intent of the programmer. For example, if dereferencing p
was a mistake, then p
should not be dereferenced.
If the intent was to increment the value referred to by p
, then parentheses can be used to ensure p
is dereferenced and then incremented. (See EXP00-C. Use parentheses for precedence of operation.)
int *p; /* ... */ (*p)++;
Another possibility is that p
is being used to reference a memory-mapped device. In this case, the variable p
should be declared as volatile
.
volatile int *p; /* ... */ (void) *(p++);
Noncompliant Code Example (if/else if)
A chain of if/else if statements is evaluated from top to bottom. At most, only one branch of the chain will be executed: the first one with a condition that evaluates to true. Consequently, duplicating a condition in a sequence of if/else if statements automatically leads to dead code.
if (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 1) /* Duplicated condition */ moveWindowToTheBackground();
Note that duplicating a condition violates this guideline only if the duplicate conditions always behave similarly…see a compliant solution below for a condition that is textually a duplicate but behaves differently.
Compliant Solution (if/else if)
In this compliant solution, the third conditional expression has been corrected.
if (param == 1) openWindow(); else if (param == 2) closeWindow(); else if (param == 3) moveWindowToTheBackground();
Compliant Solution (Conditional Side-Effects)
This code does not violate this recommendation, because even though the conditions are textually identical, they have different side effects, because the getc()
function advances the stream marker.
if (getc() == ':') readMoreInput(); else if (getc() == ':') readMoreInput(); else if (getc() == ':') readMoreInput();
Noncompliant Code Example (logical operators)
Using the same subexpression on either side of a logical operator is almost always a mistake. In this noncompliant code example, the rightmost subexpression of the controlling expression of each if
statement has no effect.
if (a == b && a == b) { // if the first one is true, the second one is too do_x(); } if (a == c || a == c ) { // if the first one is true, the second one is too do_w(); }
Compliant Solution (logical operators)
In this compliant solution, the rightmost subexpression of the controlling expression of each if
statement has been removed.
if (a == b) { do_x(); } if (a == c) { do_w(); }
Noncompliant Code Example (Unconditional Jump)
Unconditional jump statements typically has no effect.
#include <stdio.h> for (int i = 0; i < 10; ++i) { printf("i is %d", i); continue; // this is meaningless; the loop would continue anyway }
Compliant Solution (Unconditional Jump)
The continue statement has been removed from this compliant solution.
#include <stdio.h> for (int i = 0; i < 10; ++i) { printf("i is %d", i); }
Exceptions
MSC12-EX1: In some situations, seemingly dead code may make software resilient. An example is the default
label in a switch
statement whose controlling expression has an enumerated type and that specifies labels for all enumerations of the type. (See MSC01-C. Strive for logical completeness.) Because valid values of an enumerated type include all those of its underlying integer type, unless enumeration constants are provided for all those values, the default
label is appropriate and necessary.
typedef enum { Red, Green, Blue } Color; const char* f(Color c) { switch (c) { case Red: return "Red"; case Green: return "Green"; case Blue: return "Blue"; default: return "Unknown color"; /* Not dead code */ } } void g() { Color unknown = (Color)123; puts(f(unknown)); }
MSC12-EX2: It is permissible to temporarily remove code that may be needed later. (See MSC04-C. Use comments consistently and in a readable fashion for an illustration.)
MSC12-EX3: Unused functions and variables that are part of an exported library do not violate this guideline. Likewise, code that is never executed because it is #ifdef
ed out does not violate this guideline, on the grounds that it could be subsequently used in another application, or built on a different platform.
Risk Assessment
The presence of code that has no effect or is never executed can indicate logic errors that may result in unexpected behavior and vulnerabilities. Such code can be introduced into programs in a variety of ways and eliminating it can require significant analysis.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC12-C |
Low |
Unlikely |
Medium |
P2 |
L3 |
Automated Detection
Tool |
Version |
Checker |
Description |
---|---|---|---|
Astrée |
22.04 |
dead-assignment |
Supported + partially checked |
CodeSonar |
7.2p0 |
DIAG.UNEX.* |
Code not exercised by analysis |
Coverity |
2017.07 |
NO_EFFECT DEADCODE UNREACHABLE |
Finds statements or expressions that do not accomplish anything or statements that perform an unintended action. Can detect the specific instance where code can never be reached because of a logical contradiction or a dead «default» in Can detect the instances where code block is unreachable because of the syntactic structure of the code |
ECLAIR |
1.2 |
CC2.MSC12 |
Partially implemented |
GCC |
3.0 |
|
Options detect unused local variables, nonconstant static variables and unused function parameters, or unreachable code respectively. |
Helix QAC |
2022.4 |
C3110, C3112, C3307, C3404, C3426, C3427 |
|
Klocwork |
2022.4 |
CWARN.NOEFFECT.SELF_ASSIGN CWARN.NOEFFECT.UCMP.GE CWARN.NOEFFECT.UCMP.GE.MACRO CWARN.NOEFFECT.UCMP.LT CWARN.NOEFFECT.UCMP.LT.MACRO CWARN.NULLCHECK.FUNCNAME EFFECT MISRA.STMT.NO_EFFECT UNREACH.GEN UNREACH.RETURN UNREACH.SIZEOF UNREACH.ENUM LA_UNUSED VA_UNUSED.GEN VA_UNUSED.INIT INVARIANT_CONDITION.UNREACH |
|
LDRA tool suite |
9.7.1 |
8 D, 65 D, 105 D, I J, 139 S, 140 S, 57 S |
Partially implemented |
Parasoft C/C++test |
2022.2 |
CERT_C-MSC12-a |
There shall be no unreachable code in «else» block |
PC-lint Plus |
1.4 |
438, 474, 505, 522, 523, |
Fully supported |
Polyspace Bug Finder |
R2022b |
CERT C: Rec. MSC12-C |
Checks for:
Rec. partially covered. |
PRQA QA-C |
9.7 |
3110, 3112, 3307, 3404, 3426, 3427 |
Partially implemented |
RuleChecker |
22.04 |
dead-assignment |
Partially checked |
SonarQube C/C++ Plugin |
3.11 |
S1764, S2589, S2583, S1116, S1172, S1763, S1862, S1065, S1656, S2754, S1751 | |
Splint |
3.1.1 |
|
The default mode checks for unreachable code. |
PVS-Studio |
7.23 |
V551, V606, V649, V779 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
CVE-2014-1266 results from a violation of this rule. There is a spurious goto fail
statement on line 631 of sslKeyExchange.c. This goto
statement gets executed unconditionally, even though it is indented as if it were part of the preceding if
statement. As a result, the call to sslRawVerify()
(which would perform the actual signature verification) becomes dead code [ImperialViolet 2014].
Bibliography