Kartoshkas 0 / 0 / 0 Регистрация: 04.10.2021 Сообщений: 1 |
||||
1 |
||||
04.10.2021, 18:40. Показов 2667. Ответов 3 Метки micrisift visual studio 2019, си для начинающих (Все метки)
Я буквально сегодня, по какому-то видео уроку начала изучать С, вот то, что создано мной на данном этапе
Пишу я в Microsoft Visual studio, при запуске этого кода не даёт ввести чисел. После закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’. Подскажите, пожалуйста, в чём может быть проблема?
__________________
0 |
4269 / 2474 / 1338 Регистрация: 14.12.2018 Сообщений: 4,645 Записей в блоге: 1 |
|
04.10.2021, 19:11 |
2 |
Kartoshkas, заменяйте функцию
0 |
Вездепух 10452 / 5719 / 1556 Регистрация: 18.10.2014 Сообщений: 14,124 |
|
04.10.2021, 19:34 |
3 |
при запуске этого кода не даёт ввести чисел. Вы что-то выдумываете.
после закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’. Что такое «предупреждения после закрытия консоли»???
Подскажите, пожалуйста, в чём может быть проблема? Сформулируйте осмысленное описание проблемы. Пока что ничего не понятно.
0 |
easybudda Модератор 11660 / 7173 / 1704 Регистрация: 25.07.2009 Сообщений: 13,144 |
||||
04.10.2021, 20:11 |
4 |
|||
Решение
заменяйте функцию scanf() на scanf_s() …и получите обратную историю: M$VS пропустит (не факт — ругань на игнорирование результата, возвращённого scanf), а онлайн компилятор скорее всего скажет «опаньки».
Подскажите, пожалуйста, в чём может быть проблема? Проблема в заморочках компилятора от Майкрософт, про которые пишут далеко не во всех книгах по языку С, поскольку к языку это никак не относится.
Не поможет — пишите, там ещё есть танцы с бубнами…
2 |
As @SteveSummit indicates in a comment, most C implementations have a mechanism to identify functions whose return value should not be ignored.
C itself (as defined by the C standard) has always allowed a caller to ignore the return value of a function. It even allows a function declared with a return value type to not return any value as long as all callers ignore the return value.
However, that permissiveness does not generally lead to good programming practice. In some cases, it is very likely that ignoring the return value of a function will lead to a bug. scanf
is considered to be such a function, so the authors of standard libraries tend to mark scanf
as requiring that the return value be used.
There is no standard way to mark a function as requiring use of their return values. In GCC and Clang, this is done using the attribute warn_unused_result
:
int fn (int a) __attribute__ ((warn_unused_result));
(See the GCC documentation for the warn_unused_result
function attribute and how to turn off the warning (not recommended): the `-Wno-unused-result.)
In MSVC, it’s done with the _Check_return_
macro, found in sal.h
:
#include <sal.h>
_Check_return_ int fn (int a);
(See the Visual Studio docs for error C6031 and this documenation on the Source Annotation Library (sal).)
There are good reasons not to ignore the return value of any library function which uses the return value to indicate failure, including many standard library functions which do input or output. Ignoring input or output failure can lead to problems, but the problems are more evident when ignoring input failure because that can lead to the use of uninitialised values, which in turn can lead to Undefined Behaviour. That is certainly the case for scanf
: ignoring its return value means that your program will not respond correctly to malformed input, which is almost certainly a bug.
Ignoring the failure of output functions will sometimes mean that the user is not warned about failure to save persistent data. That can be serious, and it may well be that some action needs to be taken to save that data. But in other cases, the error simply means that the user didn’t see some logging message and most likely will not see future logging messages either. This might not be considered important.
As @SteveSummit indicates in a comment, most C implementations have a mechanism to identify functions whose return value should not be ignored.
C itself (as defined by the C standard) has always allowed a caller to ignore the return value of a function. It even allows a function declared with a return value type to not return any value as long as all callers ignore the return value.
However, that permissiveness does not generally lead to good programming practice. In some cases, it is very likely that ignoring the return value of a function will lead to a bug. scanf
is considered to be such a function, so the authors of standard libraries tend to mark scanf
as requiring that the return value be used.
There is no standard way to mark a function as requiring use of their return values. In GCC and Clang, this is done using the attribute warn_unused_result
:
int fn (int a) __attribute__ ((warn_unused_result));
(See the GCC documentation for the warn_unused_result
function attribute and how to turn off the warning (not recommended): the `-Wno-unused-result.)
In MSVC, it’s done with the _Check_return_
macro, found in sal.h
:
#include <sal.h>
_Check_return_ int fn (int a);
(See the Visual Studio docs for error C6031 and this documenation on the Source Annotation Library (sal).)
There are good reasons not to ignore the return value of any library function which uses the return value to indicate failure, including many standard library functions which do input or output. Ignoring input or output failure can lead to problems, but the problems are more evident when ignoring input failure because that can lead to the use of uninitialised values, which in turn can lead to Undefined Behaviour. That is certainly the case for scanf
: ignoring its return value means that your program will not respond correctly to malformed input, which is almost certainly a bug.
Ignoring the failure of output functions will sometimes mean that the user is not warned about failure to save persistent data. That can be serious, and it may well be that some action needs to be taken to save that data. But in other cases, the error simply means that the user didn’t see some logging message and most likely will not see future logging messages either. This might not be considered important.
Я использую следующий код для форматирования HRESULT
сообщения и записи сообщения в файл, только если HRESULT
является ошибкой.
Код компилируется и работает нормально, за исключением того, что я получаю следующее предупреждение компилятора:
Предупреждение C6031 Возвращаемое значение игнорируется: ‘wcsrchr’.
Я не хочу отключать предупреждение, но хочу его устранить, но я не могу понять, как это сделать? Вот минимальный компилируемый код:
// compile with: /Wall
#include <Windows.h>
#include <cwchar> // std::wcsrchr
#include <comdef.h> // _com_error
#include <iostream> // std::cin
// Show only file name instead of full path wide version
#define __FILENAME__ (std::wcsrchr(TEXT(__FILE__), L'\') ? std::wcsrchr(TEXT(__FILE__), L'\') + 1 : TEXT(__FILE__))
// Writes a sprintf-formatted string to the logging file.
#define TRACE(...) DebugLogTrace(__VA_ARGS__)
// Log HRESULTs if failed.
#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr))
{ TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }
// Writes a sprintf-formatted string to the logging file.
void DebugLogTrace(PCTSTR format_string, ...) noexcept
{
// implementation not important
}
int main()
{
// generate example failure
LOG_IF_FAILED(__FILENAME__, __LINE__, E_FAIL);
std::cin.get();
return 0;
}
Пример вывода файла для кода ошибки E_FAIL
:
7:50:11 Неизвестная ошибка
1 ответ
Лучший ответ
Мне удалось отключить предупреждение, изменив:
#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr))
{ TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }
К
#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr))
{ TRACE(TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage()); }
То есть: от { TRACE((..., ..., ..., ...)); }
до { TRACE(..., ..., ..., ...); }
Но я должен признать, что не знаю, есть ли какой-то другой непреднамеренный результат удаления лишних скобок.
1
Frodyne
3 Окт 2019 в 09:47