Некоторые операторы в C могут выполнять как математическую операцию — так и присваивание значения переменной.
Такие операторы называются составными операторами — compoud operators.
Рассмотрим пример:
#include <stdio.h>
void showPrefixAndPostfixOps() {
int num1, num2;
printf( "\nPrefix and Postfix operators... (num1 = 10)");
num1 = 10;
num2 = num1++; // num2 = 10, num1 = 11
printf( "\nnum2 = num1++; so num2 = %d and num1 = %d", num2, num1);
num1 = 10;
num2 = ++num1; // num2 = 11, num1 = 11
printf( "\nnum2 = ++num1; so num2 = %d and num1 = %d", num2, num1);
}
int main(int argc, char **argv) {
int age;
int bonus;
int a;
int b;
a = 10;
b = 2;
age = 70;
if (age > 45) {
bonus = 1000;
} else {
bonus = 500;
}
printf("Your age is %d, so your bonus is %d.\n", age, bonus);
if (age <= 70) {
printf("You are one of our youngest employees!\n");
}
if (bonus >= 1000) {
printf("You've earned a high bonus!\n");
}
printf( "\n\nHere are examples of some compound assignment operators...\n");
a = a + b;
printf( "\na + b : %d\n", a );
a = 10;
a += b;
printf( "a += b : %d\n", a );
a = 10;
a = a - b;
printf( "a - b : %d\n", a );
a = 10;
a -= b;
printf( "a -= b : %d\n", a );
a = 10;
a = a * b;
printf( "a * b : %d\n", a );
a = 10;
a *= b;
printf( "a *= b : %d\n", a );
a = 10;
a = a / b;
printf( "a/b : %d\n", a );
a = 10;
a /= b;
printf( "a /= b : %d\n", a );
a = 10;
a++;
printf( "a++ : %d\n", a );
a = 10;
a--;
printf( "a-- : %d\n", a );
showPrefixAndPostfixOps();
return(0);
}
Например:
... a += b; ...
тут оператор «+=» является составным оператором присваивания, который выполнит и сложение и присваивание полученного значения переменной a.
Список таких операторов:
| Составной оператор | Пример | Пояснение |
| += | c += 7 | c = c + 7 |
| -= | c -= 3 | c = c - 3 |
| *= | c *= 4 | c = c * 4 |
| /= | c /= 2 | c = c / 2 |
| \= | c \= 3 | c = c \ 3 |
| ^= | c ^= 2 | c = c ^ 2 |
| &= | d &= "llo" | d = d & "llo" |
Собираем, проверяем:
[simterm]
$ ./compounds
Your age is 70, so your bonus is 1000.
You are one of our youngest employees!
You've earned a high bonus!
Here are examples of some compound assignment operators...
a + b : 12
a += b : 12
a - b : 8
a -= b : 8
a * b : 20
a *= b : 20
a/b : 5
a /= b : 5
a++ : 11
a-- : 9
Prefix and Postfix operators... (num1 = 10)
num2 = num1++; so num2 = 10 and num1 = 11
num2 = ++num1; so num2 = 11 and num1 = 11
[/simterm]
Продолжение — часть 13 – операторы инкремента и декремента.

1 993 views