Почему этот приоритет оператора Java проигнорировал здесь?

Darcs является большим с этой целью.

  • я не могу ручаться за другие платформы, но в Windows это - просто единственный исполняемый файл, который Вы могли сохранить диск.
  • Самое главное, его интерактивный интерфейс командной строки является фантастическим и очень быстро становится интуитивным (я теперь действительно пропускаю интерактивные фиксации в любом VCS, который испытывает недостаток в них) - Вы не должны запоминать много команд как часть Вашего нормального рабочего процесса также. Это - главная причина, я использую ее по мерзавцу для персональных проектов.

Установка:

darcs init
darcs add -r *
darcs record -am "Initial commit"

Создание репозитория на Вашей машине лаборатории:

darcs get E:\path\to\repos

Проверка, что Вы изменили:

darcs whatsnew      # Show all changed hunks of code
darcs whatsnew -ls  # List all modified & new files

В интерактивном режиме создание нового патча от Ваших изменений:

darcs record

В интерактивном режиме продвижение исправляет в репозиторий на диске:

darcs push

Это, как известно, медленно для крупных проектов, но у меня никогда не было проблем производительности с малыми и средними персональными проектами, на которых я использовал его.

С тех пор нет никакой установки, требуемой, что Вы могли даже не учесть диск и просто захватить darcs двоичный файл от сети - если я забыл свой диск, я вытягиваю копию репозитория, я хочу продолжить работать от зеркала, я сохраняю свой webspace, затем создаю и почтовые патчи ко мне как файлы:

darcs get http://example.com/repos/forum/
# Make changes and record patches
darcs send -o C:\changes.patch

5
задан Charles 18 January 2013 в 21:36
поделиться

5 ответов

Postfix ++ increments the value of variable, and returns the value that was there before the increment. Thus, the return value of operator++ in your example will be 1, and of course 1 + 2 will give 3, which is then assigned to a. By the time of assignment, ++ has already incremented the value of a to 2 (because of precedence), so = overwrites that incremented value.

20
ответ дан 18 December 2019 в 05:21
поделиться

Operator precedence is not being ignored here.

The only slightly confusing thing about a++ is that the postfix ++ operator has two distinct effects:

  1. it increases the variable it's applied to by one
  2. it has a return value that is equal to the value of the variable before it is increased

So if a has the 1 and b has the value 2 before this line:

a = b + a++;

Then the following steps happen:

  • evaluate b
    • the expression b has the value 2, so remember the value 2
  • evaluate a++
    • the expression a++ has the value 1, so remember the value 1
    • increment the value in variable a by one, so it now holds the value 2
  • add the results of the two expressions (which are 2 and 1 respectively)
  • 2 + 1 = 3
  • assign 3 to the variable a

As you see, the code effectively assigns two values to a:

  • 2 is assigned to a during the evaluation of a++
  • 3 is assigned to a as a result of the assignment

Since the second assignment happens after the first one, you only see the effect of the second one and you will always observe a as having the value 3 after that line.

Edit: I'll try to provide an interpretation of the decompiled code. It might be a bit hard to follow, unless you know how the JVM works internally (i.e. you know how that the JVM is a stack-based VM and what that means):

   // Push the constant 1 on the stack
   0:   iconst_1
   // Pop the topmost value from the stack (1) and store it in the local variable #1 (a.k.a "a")
   1:   istore_1
   // Push the constant 2 on the stack
   2:   iconst_2
   // Pop the topmost value from the stack (2) and store it in the local variable #2 (a.k.a "b")
   3:   istore_2
   // Load the local variable #2 ("b") and push its value (2) on the stack
   4:   iload_2
   // Load the local variable #1 ("a") and push its value (1) on the stack
   5:   iload_1
   // Increment the local variable #1 by 1 (this action does not use the stack!)
   6:   iinc    1, 1
   // Pop the 2 topmost values from the stack (2 and 1), add them and push the result (3) back on the stack
   9:   iadd
   // Pop the topmost value from the stack (3) and store it in local variable #1 ("a")
   10:  istore_1

Lines 0-3 simply implement

int a=1, b=2;

The lines 4-10 implement

a = b + a++;

I've left out the other lines, as nothing interesting happens there anymore.

As an interesting sidenote: it's plainly visible that this code is not optimized at all. The reason for this is that optimization is the task of the runtime environment (i.e. the JVM) in the Java world and not of the compiler (javac for example).

13
ответ дан 18 December 2019 в 05:21
поделиться

Оператор постинкремента / декремента (a ++) возвращает значение до приращения. Преинкремент / декремент (++ a) возвращает значение после приращения.

3
ответ дан 18 December 2019 в 05:21
поделиться

This isn't a matter of precedence, it's a matter of the definition of the operator. By definition the postfix operator executes after the variable is used in the enclosing expression.

1
ответ дан 18 December 2019 в 05:21
поделиться

what the postfix ++ operator is saying is:

Use the original value of the variable in whatever equation, and then increment the variable afterwards.

0
ответ дан 18 December 2019 в 05:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: