/fp (определение поведения с плавающей запятой)/fp (Specify floating-point behavior)
Указывает, как компилятор обрабатывает выражения с плавающей запятой, оптимизации и исключения.Specifies how the compiler treats floating-point expressions, optimizations, and exceptions. Параметры /FP определяют, допускает ли сформированный код изменения среды с плавающей запятой в режим округления, маски исключений и поведение в нормальном режиме, а также указывает, будут ли проверки состояния с плавающей точкой возвращать текущие и точные результаты.The /fp options specify whether the generated code allows floating-point environment changes to the rounding mode, exception masks, and subnormal behavior, and whether floating-point status checks return current, accurate results. Он определяет, создает ли компилятор код, сохраняющий исходную операцию и упорядочение выражений, и соответствует стандарту для распространения NaN или, если вместо этого генерирует более эффективный код, который может переупорядочивать или объединять операции и использовать упрощенные преобразования алгебраические, не разрешенные стандартом.It controls whether the compiler generates code that maintains source operation and expression ordering and conforms to the standard for NaN propagation, or if it instead generates more efficient code that may reorder or combine operations and use simplifying algebraic transformations that are not allowed by the standard.
СинтаксисSyntax
/FP:[Точная | строго | Высокая скорость, | Кроме[ - ]]/fp:[precise | strict | fast | except[-]]
АргументыArguments
точенprecise
По умолчанию компилятор использует /fp:precise
поведение.By default, the compiler uses /fp:precise
behavior.
В /fp:precise
компиляторе сохраняет упорядочивание выражений источника и округление свойств кода с плавающей запятой при формировании и оптимизации объектного кода для целевого компьютера.Under /fp:precise
the compiler preserves the source expression ordering and rounding properties of floating-point code when it generates and optimizes object code for the target machine. Компилятор округляет до точности исходного кода по четырем конкретным точкам во время вычисления выражения: в назначениях при приведении типов при передаче аргумента с плавающей запятой в вызов функции и при возвращении значения с плавающей запятой из вызова функции.The compiler rounds to source code precision at four specific points during expression evaluation: at assignments, at typecasts, when a floating-point argument is passed to a function call, and when a floating-point value is returned from a function call. Промежуточные вычисления могут выполняться при точности компьютеров.Intermediate computations may be performed at machine precision. Приведение приведений можно использовать для явного округления промежуточных вычислений.Typecasts can be used to explicitly round intermediate computations.
Компилятор не выполняет преобразования алгебраические для выражений с плавающей запятой, таких как повторное связывание или распространение, если преобразование не гарантировано приводить к появлению побитового идентичного результата.The compiler does not perform algebraic transformations on floating-point expressions, such as reassociation or distribution, unless the transformation is guaranteed to produce a bitwise identical result.
Выражения, использующие специальные значения (NaN, + Infinity,-Infinity,-0,0), обрабатываются в соответствии со спецификациями IEEE-754.Expressions that involve special values (NaN, +infinity, -infinity, -0.0) are processed according to IEEE-754 specifications. Например, принимает значение, x != x
true
если x — NaN.For example, x != x
evaluates to true
if x is NaN. Контракты с плавающей точкой, то есть машинные инструкции, которые объединяют операции с плавающей запятой, могут быть созданы в разделе /fp:precise
.Floating-point contractions, that is, machine instructions that combine floating-point operations, may be generated under /fp:precise
.
Компилятор создает код, предназначенный для выполнения в среде с плавающей запятой по умолчанию , и предполагает, что среда с плавающей точкой не доступна или не изменяется во время выполнения.The compiler generates code intended to run in the default floating-point environment and assumes that the floating-point environment is not accessed or modified at runtime. То есть предполагается, что код не снимает маскировку исключений с плавающей запятой, считывает или пишет регистры состояния с плавающей запятой или изменяет режим округления.That is, it assumes that the code does not unmask floating-point exceptions, read or write floating-point status registers, or change rounding modes.
Если код с плавающей запятой не зависит от порядка операций и выражений в операторах с плавающей запятой (например, если вы не хотите, чтобы a * b + a * c
он был вычислен как (b + c) * a
или 2 * a
как a + a
), рассмотрим параметр /FP: Fast , который может создавать более быстрый и эффективный код.If your floating-point code does not depend on the order of operations and expressions in your floating-point statements (for example, if you don't care whether a * b + a * c
is computed as (b + c) * a
or 2 * a
as a + a
), consider the /fp:fast option, which can produce faster, more efficient code. Если код зависит от порядка операций и выражений, а также для доступа или изменения среды с плавающей запятой (например, для изменения режимов округления или для перехвата исключений с плавающей запятой) используйте /FP:Round.If your code both depends on the order of operations and expressions, and accesses or alters the floating-point environment (for example, to change rounding modes or to trap floating-point exceptions), use /fp:strict.
strictstrict
/fp:strict
имеет поведение, аналогичное /fp:precise
, то есть компилятор сохраняет упорядочение источника и свойства округления кода с плавающей запятой при формировании и оптимизации объектного кода для целевого компьютера, а также следит за стандартом при обработке специальных значений./fp:strict
has behavior similar to /fp:precise
, that is, the compiler preserves the source ordering and rounding properties of floating-point code when it generates and optimizes object code for the target machine, and observes the standard when handling special values. Кроме того, программа может безопасно получать доступ к среде с плавающей точкой и изменять ее во время выполнения.In addition, the program may safely access or modify the floating-point environment at runtime.
В среде /fp:strict
компилятор создает код, который позволяет программе безопасно отменять маскировку исключений с плавающей запятой, читать или записывать регистры состояния операций с плавающей запятой или изменять режимы округления.Under /fp:strict
, the compiler generates code that allows the program to safely unmask floating-point exceptions, read or write floating-point status registers, or change rounding modes. При вычислении выражения он округляет до точности исходного кода по четырем точкам: в назначениях при приведении типов с плавающей запятой в вызове функции и при возврате значения с плавающей запятой из вызова функции.It rounds to source code precision at four specific points during expression evaluation: at assignments, at typecasts, when a floating-point argument is passed to a function call, and when a floating-point value is returned from a function call. Промежуточные вычисления могут выполняться при точности компьютеров.Intermediate computations may be performed at machine precision. Приведение приведений можно использовать для явного округления промежуточных вычислений.Typecasts can be used to explicitly round intermediate computations. Компилятор не выполняет преобразования алгебраические для выражений с плавающей запятой, таких как повторное связывание или распространение, если преобразование не гарантировано приводить к появлению побитового идентичного результата.The compiler does not perform algebraic transformations on floating-point expressions, such as reassociation or distribution, unless the transformation is guaranteed to produce a bitwise identical result. Выражения, использующие специальные значения (NaN, + Infinity,-Infinity,-0,0), обрабатываются в соответствии со спецификациями IEEE-754.Expressions that involve special values (NaN, +infinity, -infinity, -0.0) are processed according to IEEE-754 specifications. Например, принимает значение, x != x
true
если x — NaN.For example, x != x
evaluates to true
if x is NaN. В не создаются контракты с плавающей точкой /fp:strict
.Floating-point contractions are not generated under /fp:strict
.
/fp:strict
является более затратным для вычислений, чем /fp:precise
потому, что компилятор должен вставлять дополнительные инструкции для перехвата исключений и позволить программам получать доступ к среде с плавающей точкой и изменять ее во время выполнения./fp:strict
is computationally more expensive than /fp:precise
because the compiler must insert additional instructions to trap exceptions and allow programs to access or modify the floating-point environment at runtime. Если код не использует эту возможность, но требует упорядочения исходного кода и округления или использует специальные значения, используйте /fp:precise
.If your code doesn't use this capability, but requires source code ordering and rounding, or relies on special values, use /fp:precise
. В противном случае рассмотрите возможность использования /fp:fast
, что может привести к быстрому и меньшему объему кода.Otherwise, consider using /fp:fast
, which can produce faster and smaller code.
быстраяfast
/fp:fast
Параметр позволяет компилятору изменять порядок, комбинировать или упростить операции с плавающей запятой, чтобы оптимизировать код с плавающей запятой для ускорения и пропускной точки.The /fp:fast
option allows the compiler to reorder, combine, or simplify floating-point operations to optimize floating-point code for speed and space. Компилятор может опускать округление в операторах присваивания, приведениях или вызовах функций.The compiler may omit rounding at assignment statements, typecasts, or function calls. Он может изменять порядок операций или выполнять преобразования алгебраические, например, используя ассоциативные и дистрибутиве законы, даже если такие преобразования приводят к наблюдаемому разному поведению округления.It may reorder operations or perform algebraic transforms, for example, by use of associative and distributive laws, even if such transformations result in observably different rounding behavior. Из-за этой улучшенной оптимизации результат некоторых вычислений с плавающей запятой может отличаться от результатов, полученных другими /fp
параметрами.Because of this enhanced optimization, the result of some floating-point computations may differ from those produced by other /fp
options. Специальные значения (NaN, + Infinity,-Infinity,-0,0) могут не распространяться или работать исключительно в соответствии со стандартом IEEE-754.Special values (NaN, +infinity, -infinity, -0.0) may not be propagated or behave strictly according to the IEEE-754 standard. В можно создавать контракты с плавающей точкой /fp:fast
.Floating-point contractions may be generated under /fp:fast
. Компилятор по-прежнему привязан к базовой архитектуре в /fp:fast
, а дополнительные оптимизации могут быть доступны с помощью параметра /Arch .The compiler is still bound by the underlying architecture under /fp:fast
, and additional optimizations may be available through use of the /arch option.
В /fp:fast
компиляторе создается код, предназначенный для выполнения в среде с плавающей запятой по умолчанию, и предполагается, что среда с плавающей запятой недоступна или не изменяется во время выполнения.Under /fp:fast
, the compiler generates code intended to run in the default floating-point environment and assumes that the floating-point environment isn't accessed or modified at runtime. То есть предполагается, что код не снимает маскировку исключений с плавающей запятой, считывает или пишет регистры состояния с плавающей запятой или изменяет режим округления.That is, it assumes that the code does not unmask floating-point exceptions, read or write floating-point status registers, or change rounding modes.
/fp:fast
предназначен для программ, не требующих полного упорядочения исходного кода и округления выражений с плавающей запятой, и не полагайтесь на стандартные правила обработки специальных значений, таких как NaN./fp:fast
is intended for programs that do not require strict source code ordering and rounding of floating-point expressions, and do not rely on the standard rules for handling special values such as NaN. Если код с плавающей запятой требует сохранения порядка исходного кода и округления или зависит от стандартного поведения специальных значений, используйте /FP: точную.If your floating-point code requires preservation of source code ordering and rounding, or relies on standard behavior of special values, use /fp:precise. Если код обращается к среде с плавающей запятой или изменяет ее, чтобы изменить режим округления, снимите маску исключений с плавающей запятой или проверьте состояние с плавающей запятой, используйте /FP:Round.If your code accesses or modifies the floating-point environment to change rounding modes, unmask floating-point exceptions, or check floating-point status, use /fp:strict.
exceptexcept
/fp:except
Параметр создает код, гарантирующий, что любые немаскированные исключения с плавающей запятой вызываются в той точке, где они происходят, и что никакие дополнительные исключения с плавающей запятой не вызываются.The /fp:except
option generates code to ensures that any unmasked floating-point exceptions are raised at the exact point at which they occur, and that no additional floating-point exceptions are raised. По умолчанию /fp:strict
параметр включает /fp:except
, а не /fp:precise
.By default, the /fp:strict
option enables /fp:except
, and /fp:precise
does not. /fp:except
Параметр несовместим с /fp:fast
.The /fp:except
option is not compatible with /fp:fast
. Параметр может быть явно отключен нами /fp:except-
.The option can be explicitly disabled by us of /fp:except-
.
Обратите внимание, что не /fp:except
включает исключения с плавающей запятой сама по себе, но необходимо, чтобы программы включили исключения с плавающей запятой.Note that /fp:except
does not enable any floating-point exceptions by itself, but it is required for programs to enable floating-point exceptions. Сведения о том, как включить исключения с плавающей запятой, см. в разделе _controlfp .See _controlfp for information on how to enable floating-point exceptions.
КомментарииRemarks
/fp
В одной командной строке компилятора можно указать несколько параметров.Multiple /fp
options can be specified in the same compiler command line. /fp:strict
/fp:fast
/fp:precise
В каждый момент времени может действовать только один из параметров, и.Only one of /fp:strict
, /fp:fast
, and /fp:precise
options can be in effect at a time. Если в командной строке указано более одного из этих параметров, параметр имеет более высокий приоритет, и компилятор выдает предупреждение.If more than one of these options is specified on the command line, the later option takes precedence and the compiler generates a warning. /fp:strict
Параметры и /fp:except
несовместимы с /clr
.The /fp:strict
and /fp:except
options are not compatible with /clr
.
Параметр /Za (совместимость с ANSI) несовместим с /fp
.The /Za (ANSI compatibility) option is not compatible with /fp
.
Использование директив компилятора для управления поведением Floating-PointUsing Compiler Directives to Control Floating-Point Behavior
Компилятор предоставляет три директивы директивы pragma для переопределения поведения с плавающей запятой, указанного в командной строке: float_control, fenv_accessи fp_contract.The compiler provides three pragma directives to override the floating-point behavior specified on the command-line: float_control, fenv_access, and fp_contract. Эти директивы можно использовать для управления поведением операций с плавающей запятой на уровне функций, а не внутри функции.You can use these directives to control floating-point behavior at function-level, not within a function. Обратите внимание, что эти директивы не соответствуют непосредственно /fp
параметрам.Note that these directives do not correspond directly to the /fp
options. В этой таблице показано, как /fp
директивы Options и pragma сопоставляются друг с другом.This table shows how the /fp
options and pragma directives map to each other. Дополнительные сведения см. в документации по отдельным параметрам и директивам директивы pragma.For more information, see the documentation for the individual options and pragma directives.
ПараметрOption | float_control (точное)float_control(precise) | float_control (за исключением)float_control(except) | fenv_accessfenv_access | fp_contractfp_contract |
---|---|---|---|---|
/fp:fast |
offoff | offoff | offoff | onon |
/fp:precise |
onon | offoff | offoff | onon |
/fp:strict |
onon | onon | onon | offoff |
Среда с плавающей точкой по умолчаниюThe default floating point environment
При инициализации процесса устанавливается Среда с плавающей точкой по умолчанию .When a process is initialized, the default floating point environment is set. Эта среда маскирует все исключения с плавающей запятой, устанавливает режим округления для округления до ближайшего ( FE_TONEAREST
), сохраняет значения поднормали (денормализованные), использует точность по умолчанию значащим (мантисса) для float
double
значений, и long double
, и, где поддерживается, устанавливает элемент управления бесконечности в режим аффинных по умолчанию.This environment masks all floating point exceptions, sets the rounding mode to round to nearest (FE_TONEAREST
), preserves subnormal (denormal) values, uses the default precision of significand (mantissa) for float
, double
, and long double
values, and where supported, sets the infinity control to the default affine mode.
Доступ и изменение среды с плавающей точкойFloating-point environment access and modification
Среда выполнения Microsoft Visual C++ предоставляет несколько функций для доступа к среде с плавающей запятой и ее изменения.The Microsoft Visual C++ runtime provides several functions to access and modify the floating-point environment. К ним относятся _controlfp, _clearfpи _statusfp , а также их варианты.These include _controlfp, _clearfp, and _statusfp and their variants. Чтобы обеспечить правильное поведение программы, когда код обращается к среде с плавающей запятой или изменяет ее, fenv_access
необходимо включить параметр либо с помощью /fp:strict
параметра, либо с помощью fenv_access
директивы pragma, чтобы эти функции имели любой результат.To ensure correct program behavior when your code accesses or modifies the floating-point environment, fenv_access
must be enabled, either by the /fp:strict
option or by use of the fenv_access
pragma, for these functions to have any effect. Если fenv_access
параметр не включен, доступ или изменение среды с плавающей запятой может привести к непредвиденному поведению программы: код может не учитывать запрошенные изменения в среде с плавающей запятой; регистры состояния с плавающей запятой не могут сообщать ожидаемые или текущие результаты, а непредвиденные исключения с плавающей запятой могут не возникать.When fenv_access
is not enabled, access or modification of the floating-point environment may result in unexpected program behavior: code may not honor requested changes to the floating-point environment; the floating-point status registers may not report expected or current results; and unexpected floating-point exceptions may occur or expected floating-point exceptions may not occur.
Когда код обращается к среде с плавающей запятой или изменяет ее, необходимо соблюдать осторожность при объединении кода fenv_access
с включенным кодом, который не fenv_access
включен.When your code accesses or modifies the floating-point environment, you must be careful when you combine code where fenv_access
is enabled with code that does not have fenv_access
enabled. В коде fenv_access
, где не включено, компилятор предполагает, что используется среда с плавающей запятой по умолчанию платформы и что состояние с плавающей запятой недоступно или не изменено.In code where fenv_access
is not enabled, the compiler assumes that the platform default floating-point environment is in effect, and that the floating-point status is not accessed or modified. Рекомендуется сохранить и восстановить локальную среду с плавающей запятой до состояния по умолчанию перед передачей управления в функцию, которая не fenv_access
включена.We recommend you save and restore the local floating-point environment to its default state before control is transferred to a function that does not have fenv_access
enabled. В этом примере показано, как float_control
можно установить и восстановить директиву pragma:This example demonstrates how the float_control
pragma can be set and restored:
#pragma float_control(strict, on, push)
// Code that uses /fp:strict mode
#pragma float_control(pop)
Режимы округления с плавающей запятойFloating-point rounding modes
В /fp:precise
и /fp:fast
компилятор создает код, предназначенный для выполнения в среде с плавающей запятой по умолчанию, и предполагает, что среда недоступна или изменена во время выполнения.Under both /fp:precise
and /fp:fast
the compiler generates code intended to run in the default floating-point environment and assumes that the environment isn't accessed or modified at runtime. То есть предполагается, что код не снимает маскировку исключений с плавающей запятой, считывает или пишет регистры состояния с плавающей запятой или изменяет режим округления.That is, it assumes that the code does not unmask floating-point exceptions, read or write floating-point status registers, or change rounding modes. Однако некоторым программам необходимо изменить среду с плавающей запятой.However, some programs need to alter the floating-point environment. Например, в этом образце вычисляются ошибки, связанные с операциями умножения с плавающей запятой путем изменения режима округления с плавающей запятой.For example, this sample computes error bounds of a floating-point multiplication by altering floating-point rounding modes:
// fp_error_bounds.cpp
#include <iostream>
#include <limits>
using namespace std;
int main(void)
{
float a = std::<float>::max();
float b = -1.1;
float cLower = 0.0;
float cUpper = 0.0;
unsigned int control_word = 0;
int err = 0;
// compute lower error bound.
// set rounding mode to -infinity.
err = _controlfp_s(&control_word, _RC_DOWN, _MCW_RC);
if (err)
{
cout << "_controlfp_s(&control_word, _RC_DOWN, _MCW_RC) failed with error:" << err << endl;
}
cLower = a * b;
// compute upper error bound.
// set rounding mode to +infinity.
err = _controlfp_s(&control_word, _RC_UP, _MCW_RC);
if (err)
{
cout << "_controlfp_s(&control_word, _RC_UP, _MCW_RC) failed with error:" << err << endl;
}
cUpper = a * b;
// restore default rounding mode.
err = _controlfp_s(&control_word, _CW_DEFAULT, _MCW_RC);
if (err)
{
cout << "_controlfp_s(&control_word, _CW_DEFAULT, _MCW_RC) failed with error:" << err << endl;
}
// display error bounds.
cout << "cLower = " << cLower << endl;
cout << "cUpper = " << cUpper << endl;
return 0;
}
Так как компилятор предполагает, что среда с плавающей запятой по умолчанию находится в /fp:fast
, и вы /fp:precise
можете игнорировать вызовы _controlfp_s
. Например, при компиляции с использованием /O2
и /fp:precise
для архитектуры x86, границы не вычисляются, а образец программы выводит:For example, when compiled by using both /O2
and /fp:precise
for the x86 architecture, the bounds are not computed, and the sample program outputs:
cLower = -inf
cUpper = -inf
При компиляции с обеих /O2
/fp:strict
платформ и для архитектуры x86 пример программы выводит:When compiled with both /O2
and /fp:strict
for the x86 architecture, the sample program outputs:
cLower = -inf
cUpper = -3.40282e+38
Специальные значения с плавающей точкойFloating-point special values
В условиях /fp:precise
и /fp:strict
выражениях, в которых используются специальные значения (NaN, + Infinity,-Infinity,-0,0), ведут себя в соответствии со спецификациями IEEE-754.Under /fp:precise
and /fp:strict
, expressions that involve special values (NaN, +infinity, -infinity, -0.0) behave according to the IEEE-754 specifications. В среде /fp:fast
поведение этих специальных значений может не соответствовать стандарту IEEE-754.Under /fp:fast
, the behavior of these special values may be inconsistent with IEEE-754.
В этом примере демонстрируется другое поведение специальных значений в разделе /fp:precise
, /fp:strict
а также /fp:fast
:This sample demonstrates the different behavior of special values under /fp:precise
, /fp:strict
and /fp:fast
:
// fp_special_values.cpp
#include <stdio.h>
#include <cmath>
float gf0 = -0.0;
int main()
{
float f1 = INFINITY;
float f2 = NAN;
float f3 = -INFINITY;
bool a, b;
float c, d, e;
a = (f1 == f1);
b = (f2 == f2);
c = (f1 - f1);
d = (f2 - f2);
printf("INFINITY == INFINITY : %d\n", a);
printf("NAN == NAN : %d\n", b);
printf("INFINITY - INFINITY : %f\n", c);
printf("NAN - NAN : %f\n", d);
e = gf0 / abs(f3);
printf("std::signbit(-0.0/-INFINITY): %d\n", std::signbit(c));
return 0;
}
При компиляции с /O2
/fp:precise
/O2
/fp:strict
архитектурой или для архитектуры x86 выходные данные согласуются со спецификацией IEEE-754:When compiled with /O2
/fp:precise
or /O2
/fp:strict
for x86 architecture, the outputs are consistent with the IEEE-754 specification:
INFINITY == INFINITY : 1
NAN == NAN : 0
INFINITY - INFINITY : -nan(ind)
NAN - NAN : -nan(ind)
std::signbit(-0.0/-INFINITY): 1
При компиляции с /O2
/fp:fast
архитектурой для x86 выходные данные не согласуются с IEEE-754:When compiled with /O2
/fp:fast
for x86 architecture, the outputs are not consistent with IEEE-754:
INFINITY == INFINITY : 1
NAN == NAN : 1
INFINITY - INFINITY : 0.000000
NAN - NAN : 0.000000
std::signbit(-0.0/-INFINITY): 0
Преобразования алгебраические с плавающей точкойFloating-point algebraic transformations
В /fp:precise
и /fp:strict
компилятор не выполняет математические преобразования, за исключением случаев, когда преобразование гарантированно создает побитовый идентичный результат.Under /fp:precise
and /fp:strict
, the compiler does not perform mathematical transformations unless the transformation is guaranteed to produce a bitwise identical result. Компилятор может выполнять такие преобразования в /fp:fast
.The compiler may perform such transformations under /fp:fast
. Например, выражение a * b + a * c
в функции Sample algebraic_transformation
может быть скомпилировано в a * (b + c)
разделе /fp:fast
.For example, the expression a * b + a * c
in the sample function algebraic_transformation
may be compiled into a * (b + c)
under /fp:fast
. Такие преобразования не выполняются в /fp:precise
или /fp:strict
, а компилятор создает a * b + a * c
.Such transformations aren't performed under /fp:precise
or /fp:strict
, and the compiler generates a * b + a * c
.
float algebraic_transformation (float a, float b, float c)
{
return a * b + a * c;
}
Явные точки приведения с плавающей точкойFloating-point explicit casting points
В разделе /fp:precise
и /fp:strict
компилятор округляет до точности исходного кода на четырех конкретных точках во время вычисления выражения: в назначениях при приведении типов при передаче аргумента с плавающей запятой в вызов функции и при возвращении значения с плавающей запятой из вызова функции.Under /fp:precise
and /fp:strict
, the compiler rounds to source code precision at four specific points during expression evaluation: at assignments, at typecasts, when a floating-point argument is passed to a function call, and when a floating-point value is returned from a function call. Приведение приведений можно использовать для явного округления промежуточных вычислений.Typecasts can be used to explicitly round intermediate computations. В среде /fp:fast
компилятор не создает явные приведения на этих точках, чтобы гарантировать точность исходного кода.Under /fp:fast
, the compiler does not generate explicit casts at these points to guarantee source code precision. В этом примере демонстрируется поведение при различных /fp
параметрах.This sample demonstrates the behavior under different /fp
options:
float casting(float a, float b)
{
return 5.0*((double)(a+b));
}
При компиляции с помощью /O2
/fp:precise
или /O2
/fp:strict
можно увидеть, что явные приведения типов вставляются как в приведении, так и в точке возврата функции в созданном коде для архитектуры x64:When compiled by using /O2
/fp:precise
or /O2
/fp:strict
, you can see that explicit type casts are inserted at both the typecast and at the function return point in the generated code for the x64 architecture:
addss xmm0, xmm1
cvtss2sd xmm0, xmm0
mulsd xmm0, QWORD PTR __real@4014000000000000
cvtsd2ss xmm0, xmm0
ret 0
В /O2
/fp:fast
созданном коде упрощен, так как все приведения типов оптимизированы:Under /O2
/fp:fast
the generated code is simplified, because all type casts are optimized away:
addss xmm0, xmm1
mulss xmm0, DWORD PTR __real@40a00000
ret 0
Установка данного параметра компилятора в среде разработки Visual StudioTo set this compiler option in the Visual Studio development environment
Откройте диалоговое окно Страницы свойств проекта.Open the project's Property Pages dialog box. Подробнее см. в статье Настройка компилятора C++ и свойства сборки в Visual Studio.For details, see Set C++ compiler and build properties in Visual Studio.
Выберите страницу свойств Свойства " > Создание кода C/C++" > .Select the Configuration Properties > C/C++ > Code Generation property page.
Измените свойство модель с плавающей точкой .Modify the Floating Point Model property.
Установка данного параметра компилятора программным способомTo set this compiler option programmatically
- См. раздел floatingPointModel.See floatingPointModel.
См. также разделSee also
Параметры компилятора MSVCMSVC Compiler Options
Синтаксис Command-Line компилятора КОМПИЛЯТОРОМ MSVCMSVC Compiler Command-Line Syntax