Order of evaluation
Материал из cppreference.com
|
|
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Порядок вычисления операндов любого оператора C, в том числе порядок вычисления аргументов функции в функцию вызова выражения, а также порядок оценки подвыражений в любое выражение не определено (за исключением случаев, указанных ниже). Компилятор будет оценивать их в любом порядке, и, возможно, выбрать другой порядок, когда же выражение вычисляется снова.
Original:
Order of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует нет понятия слева-направо или справа-налево оценки в C, который не следует путать с слева-направо и справа-налево ассоциативность операторов: выражение
a + b + c анализируется как из-за (a + b) + c налево-направо ассоциативность оператора +, но подвыражение c может быть оценена первый (или последний, или в то же время, как a или b) во время выполнения.Original:
There is no concept of left-to-right or right-to-left evaluation in C, which is not to be confused with left-to-right and right-to-left associativity of operators: the expression
a + b + c is parsed as (a + b) + c due to left-to-right associativity of operator+, but the subexpression c may be evaluated first (or last, or at the same time as a or b) at run time.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Содержание |
[править] Определения
[править] Оценки
Есть два вида оценок выполняется компилятором для каждого выражения или подвыражения (оба из которых являются необязательными):
Original:
There are two kinds of evaluations performed by the compiler for each expression or subexpression (both of which are optional):
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- ' Вычисления значения: расчет значения, возвращаемого выражением. Это может включать определение идентичности объекта (именующее оценке) или считывания значения, присвоенные объекту (RValue оценки)Original:value computation: calculation of the value that is returned by the expression. This may involve determination of the identity of the object (lvalue evaluation) or reading the value previously assigned to an object (rvalue evaluation)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - ' Побочный эффект: доступ (чтение или запись) для объекта, указанного летучих glvalue, изменение (запись) на объект, изменяя файл, изменения плавающей точкой окружающей среды (если поддерживается), или вызове функции, которая делает любой из этих операций.Original:side effect: access (read or write) to an object designated by a volatile glvalue, modification (writing) to an object, modifying a file, modifying the floating-point environment (if supported), or calling a function that does any of those operations.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Если нет побочных эффектов от выражения мнения и компилятор может определить, что это значение не используется, то выражение не вычисляется.
Original:
If no side effects are produced by an expression and the compiler can determine that the value is not used, the expression is not evaluated.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Заказ
"Последовательный-до» является асимметричным, транзитивным парных отношений между оценками в том же потоке (она может распространяться на темы, если атомарные типы памяти и барьеры участвуют).
Original:
"sequenced-before" is an asymmetric, transitive, pair-wise relationship between evaluations within the same thread (it may extend across threads if atomic types and memory barriers are involved).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
- Если последовательность точка находится между подвыражений Е1 и Е2, то и расчет стоимости и побочных эффектов E1 являются последовательными перед каждым вычислением стоимости и побочных эффектов E2Original:If a sequence point is present between the subexpressions E1 and E2, then both value computation and side effects of E1 are sequenced before every value computation and side effect of E2The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если оценка секвенируют до оценку B, то оценка будет завершена до оценки B начинается. (начиная с C11)Original:If evaluation A is sequenced before evaluation B, then evaluation of A will be complete before evaluation of B begins. (начиная с C11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если не последовательно до B и B секвенируют до, то оценка B будет завершена до оценки начинается. (начиная с C11)Original:If A is not sequenced before B and B is sequenced before A, then evaluation of B will be complete before evaluation of A begins. (начиная с C11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Если не последовательно до B и B не последовательно, прежде чем, то две возможности: (начиная с C11)Original:If A is not sequenced before B and B is not sequenced before A, then two possibilities exist: (начиная с C11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - * Оценки А и В непоследовательными: они могут быть выполнены в любом порядке и могут перекрывать друг друга (в пределах одного потока исполнения, компилятор может чередовать инструкции процессора, которые содержат А и В)Original:* evaluations of A and B are unsequenced: they may be performed in any order and may overlap (within a single thread of execution, the compiler may interleave the CPU instructions that comprise A and B)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - * Оценки А и В indeterminably-последовательность: они могут быть выполнены в любом порядке, но не могут пересекаться: либо будет завершена до B, или B будет завершена до A. порядок может быть противоположным в следующий раз то же самое Выражение вычисляется.Original:* evaluations of A and B are indeterminably-sequenced: they may be performed in any order but may not overlap: either A will be complete before B, or B will be complete before A. The order may be the opposite the next time the same expression is evaluated.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Правила
1)Существует последовательность момент после оценки всех аргументов функции и функции обозначения, и до фактического вызова функции.
2) Original:
There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Значение вычислений (но не побочных эффектов) из операндов любого оператора последовательно до значения вычисления результата оператора (но не его побочные эффекты). (начиная с C11)
3) Original:
The value computations (but not the side-effects) of the operands to any operator are sequenced before the value computation of the result of the operator (but not its side-effects). (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку после оценки первого (левого) операнда и до оценки второй (правой) операнда из следующих бинарных операторов:
4) && (логическое И), || (логическое ИЛИ), и , (запятая).Original:
There is a sequence point after evaluation of the first (left) operand and before evaluation of the second (right) operand of the following binary operators:
&& (logical AND), || (logical OR), and , (comma).The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку после оценки первого (левого) операнда и до оценки второй или третий операнд (в зависимости от оцениваются) условного
5) ?: оператораOriginal:
There is a sequence point after evaluation of the first (left) operand and before evaluation of the second or third operand (whichever is evaluated) of the conditional operator
?:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Побочный эффект (изменение левого аргумента) прямого оператор присваивания и всех операторов присваивания секвенируют после вычисления значения (но не побочных эффектов) как левый и правый аргументы. (начиная с C11)
6) Original:
The side effect (modification of the left argument) of the direct assignment operator and of all compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments. (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Значение вычисления постинкремента и Постфиксный декремент операторов последовательно до его побочный эффект. (начиная с C11)
7) Original:
The value computation of the postincrement and postdecrement operators is sequenced before its side-effect. (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку в конце полного описателя. (начиная с C99)
8) Original:
There is a sequence point at the end of a full declarator. (начиная с C99)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку после оценки полного выражения (выражение, которое не является подвыражение: обычно то, что заканчивается точкой с запятой или управление заявление, если переключатель / / а / делать), и до следующего полного выражения.
9) Original:
There is a sequence point after the evaluation of a full expression (an expression that is not a subexpression: typically something that ends with a semicolon or a controlling statement of if/switch/while/do) and before the next full expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку непосредственно перед возвращением в библиотеку функций. (начиная с C99)
10) Original:
There is a sequence point immediately before the return of a library function. (начиная с C99)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Существует последовательность точку после действия, связанные с каждым спецификатор преобразования в форматированный I / O. (начиная с C99)
11) Original:
There is a sequence point after the action associated with each conversion specifier in formatted I/O. (начиная с C99)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Есть последовательность пунктов до и сразу после каждого вызова функции сравнения, сделанные библиотечных функций qsort и bsearch, а также между любой вызов функции сравнения и движения соответствующих предметов, изготовленных qsort (начиная с C99)
12) Original:
There are sequence points before and immediately after each call to a comparison function made by the library functions qsort and bsearch, as well as between any call to the comparison function and the movement of the associated objects made by qsort (начиная с C99)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Вызов функции, которые не последовательно, до или последовательно за другой вызов функции неопределенно последовательности (инструкции процессора, которые представляют собой различные вызовы функции не могут чередоваться, даже если функции встроенных) (начиная с C11)
13) Original:
A function call that is not sequenced before or sequenced after another function call is indeterminately sequenced (CPU instructions that constitute different function calls cannot be interleaved, even if the functions are inlined) (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
В выражениях инициализации списка всех оценок неопределенно последовательно (начиная с C11)
14) Original:
In initialization list expressions, all evaluations are indeterminately sequenced (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
В отношении неопределенно-последовательность вызова функции, операции присваивания операторы, и префикса и постфикса формы операторов инкремента и декремента являются одной оценки. (начиная с C11)
Original:
With respect to an indeterminately-sequenced function call, the operation of compound assignment operators, and both prefix and postfix forms of increment and decrement operators are single evaluations. (начиная с C11)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] Неопределенное поведение
1)Если побочный эффект на скалярный объект непоследовательными по отношению к другим побочным эффектом того же объекта скаляр, поведение не определено.
Original:
If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
i = ++i + i++; // undefined behavior
i = i++ + 1; // undefined behavior
f(++i, ++i); // undefined behavior
f(i = -1, i = -1); // undefined behavior
Если побочный эффект на скалярный объект непоследовательными по отношению к значению вычисления с использованием значения одного и того же объекта скаляр, поведение не определено.
Original:
If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
f(i, i++); // undefined behavior
a[i] = i++; // undefined bevahior
Приведенные выше правила применяются до тех пор, пока хотя бы один допустимый заказа подвыражений допускает такое непоследовательное побочный эффект.
Original:
The above rules apply as long as at least one allowable ordering of subexpressions permits such an unsequenced side-effect.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[править] См. также
Приоритет операторов который определяет, как выражения строятся из их представление исходного кода.
Original:
Приоритет операторов which defines how expressions are built from their source code representation.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.