[humor] Задачка для 40-летнего одмина
в Java - 14, в Perl - 13.
++i + ++i + ++i
++i + ++i + ++i + ++i
и т.д.
В php это тогда будет выглядеть как-то так:
<?php
class int {
private $content;
public function __construct($content) {
$this->content = $content;
}
public function inc {
$this->content++;
return $this;
}
public function get_content {
return $this->content;
}
public static function add(int $a,int $b) {
return new self($a->get_content+$b->get_content;
}
}
$i = new int(5);
$i = int::add($i->inc$i->inc;
?>
имхо даже в С результат может отличаться для разных компиляторов.
В C, кажется, вообще может быть и 13 и 14.
то есть если бы я к нему постучался и написал 13, то это тоже было бы правильно? =)
то есть если бы я к нему постучался и написал 13, то это тоже было бы правильно? =)Не факт, что он об этом знает.
то есть если бы я к нему постучался и написал 13, то это тоже было бы правильно? =)это все равно, что на вопрос "сколько будет 0/0?" дать ответ "13, потому что проверка: 13*0 = 0"
++i + (++i + ++i) vs (++i + ++i) + ++i
не то же самое, так как тут количество ответов ограничено 2-мя (13 и 14).
он самый
> имхо даже в С результат может отличаться для разных компиляторов.
а если оптимизатор еще включить... ууу...
ограничено 2-мяимхо, неправильно
5.1.2.3 Program execution
2 Accessing a volatile object, modifying an object, modifying a file, or calling a function
that does any of those operations are all side effects,11) which are changes in the state of
the execution environment. Evaluation of an expression may produce side effects. At
certain specified points in the execution sequence called sequence points, all side effects
of previous evaluations shall be complete and no side effects of subsequent evaluations
shall have taken place. (A summary of the sequence points is given in annex C.)
Annex C
(informative)
Sequence points
1 The following are the sequence points described in 5.1.2.3:
— The call to a function, after the arguments have been evaluated (6.5.2.2).
— The end of the first operand of the following operators: logical AND && (6.5.13);
logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).
— The end of a full declarator: declarators (6.7.5);
— The end of a full expression: an initializer (6.7.8); the expression in an expression
statement (6.8.3); the controlling expression of a selection statement (if or switch)
(6.8.4); the controlling expression of a while or do statement (6.8.5); each of the
expressions of a for statement (6.8.5.3); the expression in a return statement
(6.8.6.4).
— Immediately before a library function returns (7.1.4).
— After the actions associated with each formatted input/output function conversion
specifier (7.19.6, 7.24.2).
— Immediately before and immediately after each call to a comparison function, and
also between any call to a comparison function and any movement of the objects
passed as arguments to that call (7.20.5).
В обоих случаях получится 22?
в первом вроде 24.
Да?
А, да...
KoloDen
Привет, я общительный пацан, люблю поболтать, особенно с классными девченками.
хм...
то есть если бы я к нему постучался и написал 13, то это тоже было бы правильно?
В языках программирования не бывает такой неоднозначности.
---
"Я знаю правду! Все прежние правды --- прочь!"
---
я знаю правду, все прочие правды знает кохтпа
в Java - 14,Наглая ложь:
public class add {
public static void main(String [] args) {
int i = 5;
i = ++i + ++i;
System.out.println(i);
}
}
Дает 13, как и положено по спецификации:
Процитировал 3-ю спецификацию. Во второй - абсолютно то же самое.
5.7.1 Evaluate Left-Hand Operand First
The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-hand operand is evaluated. For example, if the left-hand operand contains an assignment to a variable and the right-hand operand contains a reference to that same variable, then the value produced by the reference will reflect the fact that the assignment occurred first.
....
15.15.1 Prefix Increment Operator ++
A unary expression preceded by a ++ operator is a prefix increment expression. The result of the unary expression must be a variable of a type that is convertible (§5.1.8) to a numeric type, or a compile-time error occurs. The type of the prefix increment expression is the type of the variable. The result of the prefix increment expression is not a variable, but a value.
At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable after the new value is stored.
Ну и при увеличении количества ++i будет 21, 30 и т.д. соответственно.
А ещё написать в TeXовских обзначениях степень n^m и скормить это в c++.
int i = 5;
i = ++i + ++i;
дает на С++ 14, а на РНР 13, потому что у них РАЗНЫЕ СИСТЕМЫ ПРИОРИТЕТОВ, РАЗНЫЙ СИНТАКСИС МАТЕМАТИКИ, и это все есть в ДОКУМЕНТАЦИИ.
В С++ пред-инкремент выполняется, как и положено пред-инкременту, ДО вычисления выражения:
1) прибавить единицу к i
2) прибавить единицу к i
3) получить левое слагаемое
4) получить правое слагаемое
5) сложить оба
В РНР пред-инкремент - это просто операция с высоким приоритетом. Кстати, из-за этого уродства приобретает важное значение то, которая из не связанных между собой больше ничем операций одинакового высокого приоритета выполняется первой - совершенно дикая архитектура.
1) прибавить единицу к i
2) получить левое слагаемое
3) прибавить единицу к i
4) получить правое слагаемое
5) сложить оба
Вот так. Учите матчасть, самоучки, читайте доки, а бугогайствовать все умеют.
по поводу с++ чувак отжог
Я их местами перепутал.
Оставить комментарий
Fragaria
Преамбула:Амбула:
В C этот пример выдаёт 14, а в PHP - 13. Объясните, почему и в чём разница? Чисто логически мне кажется, что должно быть 13.