Using Compound Assignment Operators in C: A Beginner's Guide


An assignment operator is used for assigning a value to a variable. The most common assignment operator is =(equal). The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.


Compound OperatorSample ExpressionExpanded Form
+= a+=5 a=a+5
-= a-=6 a=a-6
*= a*=7 a=a*7
/= a/=4 a=a/4
%= a%=9 a=a%9

The code is a C program that demonstrates the use of compound assignment operators in C. Here is an explanation of each line of the code:

  • int a=10,b=5; declares two variables a and b of type int and assigns them the values 10 and 5 respectively.
  • a+=b; is the compound assignment operator +=, it performs a+b and assigns the value to a. It is equivalent to a=a+b.
  • printf("A : %d",a); prints the value of a which is 15, this is the result after using += operator.
  • a-=10; is the compound assignment operator -=, it performs a-10 and assigns the value to a. It is equivalent to a=a-10.
  • printf("\nA : %d",a); prints the value of a which is 5, this is the result after using -= operator.
  • return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.

When you run this code, it will perform the compound assignment operation on variables and print the results in the console.


Source Code

//Assignment operator
 
#include<stdio.h>
int main()
{
    int a=10,b=5;
    //+=
    a+=b; //a=a+5
    printf("A : %d",a); //15
    a-=10; //a=a-10
    printf("\nA : %d",a);
    return 0;
}
 
To download raw file Click Here

Output

A : 15
A : 5

List of Programs


Sample Programs


Switch Case in C


Conditional Operators in C


Goto Statement in C


While Loop Example Programs


Looping Statements in C

For Loop Example Programs


Array Examples in C

One Dimensional Array


Two Dimensional Array in C


String Example Programs in C


Functions Example Programs in C