Skip to content
EntityQ4820439· pop 5· linked from 15 articles

atribuição ampliada

Sign in to save

Also known as compound assignment

a type of assignment operator where an operator takes a variable as one of its arguments and then assigns the result back to the same variable

Described at

Compound Assignment Operators in Java - GeeksforGeeks

Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more., Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

geeksforgeeks.org

In Java, compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on two operands before assigning the result to the first operand. At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions: First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs. Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable. First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs. Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs. Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown. Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown. Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. Note: Here, 6.6 which is double is automatically converted to short without explicit type-casting. Refer: When is the Type-conversion required? Now, we are going to understand the difference between normal assignment and compound assignment with the help of practical examples for better understanding.

Excerpt from a page describing this subject · 17,544 chars · not written by Vinony

Article · Português

Atribuição ampliada (ou atribuição composta) são certos em algumas linguagens de programação (especialmente aquelas derivadas de C). Uma atribuição ampliada geralmente é utilizada para substituir uma declaração onde um operador toma uma variável como um de seus argumentos e então atribui o resultado de volta à mesma variável. Por exemplo, a seguinte declaração, ou alguma variação desta, pode ser encontrada em vários programas: x = x + 1 Isto significa "encontrar o número armazenado na variável x, adicionar 1 a ele, e armazenar o resultado da adição na variável x". Por mais simples que pareça, esta operação possuir uma ineficiência, na medida em que a localização da variável x deve ser pesquisada duas vezes se o compilador não reconhecer as duas partes da expressão como idênticas: x pode ser uma referência para algum lemento de arranjo ou possuir outra complexidade. Em comparação, a seguir está uma versão da atribuição ampliada: x += 1 Com esta versão, não há desculpa para a falha de compilador para gerar o código que procura a loca~lização da variável x apenas uma vez, e modifica-o no local, obviamente se o código de máquina suportar tal sequência. Por exemplo, se x for uma variável simples, a sequência de código da máquina pode ser algo como <pre>Load xAdd 1Store x</pre> e o mesmo código poderia ser gerado para ambas as formas. Mas se há um código op especial, poderia ser <pre> MDM x,1</pre> significando "Modificar Memória" pela adição de 1 à x e um compilador adequado geraria o mesmo código para as duas formas. Alguns códigos de máquina oferecem operações INC e DEC (para adicionar ou subtrair unidade), outras podem permitir outas constantens além de um. Geralmente, a forma é <pre>x += expressão</pre> e não haverá códigos op especiais para auxiliar. Ainda há a possibilidade que se x for uma entidade complexa o compilador será estimulado a evitar duplicação ao acessar x e, obviamente, se x for um nome longo, haverá menos digitação exigida. Esta última foi a base da funcionalidade similar nos compiladores Algol oferecidos através dos sistemas Burroughts B6700, usando o símbolo tilda para suportar a variável que sendo atribuída, de modo que <pre>NomeLongo:=x + sqrt(NomeLongo)*7;</pre> seria <pre>NomeLongo:=x + sqrt(~)*7;</pre> e assim por diante. Isto é mais geral que apenas x:=~ + 1;. Produzir código otimizado continuaria sendo a competência do compilador.

Abstract from DBpedia / Wikipedia · CC BY-SA

Available in 5 languages

via Wikidata sitelinks · CC0