📜  C / C++中的赋值运算符

📅  最后修改于: 2021-05-25 19:14:39             🧑  作者: Mango

赋值运算符用于为变量赋值。赋值运算符的左侧操作数是一个变量,而赋值运算符的右侧操作数是一个值。右侧的值必须与左侧的变量具有相同的数据类型,否则编译器将引发错误。
不同类型的赋值运算符如下所示:

  • “ =” :这是最简单的赋值运算符。该运算符用于将右侧的值分配给左侧的变量。
    例如:
    a = 10;
    b = 20;
    ch = 'y';
    
  • “ + =” :此运算符是’+’和’=’运算符。该运算符首先将左侧变量的当前值添加到右侧的值,然后将结果分配给左侧的变量。
    例子:
    (a += b) can be written as (a = a + b)
    

    如果存储在a中的初始值是5。那么(a + = 6)= 11。

  • “-=”此运算符是’-‘和’=’运算符。该运算符首先从右侧的值中减去左侧变量的当前值,然后将结果分配给左侧的变量。
    例子:
    (a -= b) can be written as (a = a - b)
    

    如果存储在a中的初始值是8,则(a-= 6)= 2。

  • “ * =”此运算符是’*’和’=’运算符。该运算符首先将左侧变量的当前值乘以右侧值,然后将结果分配给左侧变量。
    例子:
    (a *= b) can be written as (a = a * b)
    

    如果最初存储在a中的值为5。则(a * = 6)= 30。

  • “ / =”此运算符是’/’和’=’运算符。该运算符首先将左侧变量的当前值除以右侧值,然后将结果分配给左侧变量。
    例子:
    (a /= b) can be written as (a = a / b)
    

    如果存储在a中的初始值是6。则(a / = 2)= 3。

以下示例说明了各种赋值运算符:

C
// C program to demonstrate
// working of Assignment operators
  
#include 
  
int main()
{
  
    // Assigning value 10 to a
    // using "=" operator
    int a = 10;
    printf("Value of a is %d\n", a);
  
    // Assigning value by adding 10 to a
    // using "+=" operator
    a += 10;
    printf("Value of a is %d\n", a);
  
    // Assigning value by subtracting 10 from a
    // using "-=" operator
    a -= 10;
    printf("Value of a is %d\n", a);
  
    // Assigning value by multiplying 10 to a
    // using "*=" operator
    a *= 10;
    printf("Value of a is %d\n", a);
  
    // Assigning value by dividing 10 from a
    // using "/=" operator
    a /= 10;
    printf("Value of a is %d\n", a);
  
    return 0;
}


C++
// C++ program to demonstrate 
// working of Assignment operators 
  
#include 
using namespace std;
  
int main() 
{ 
  
    // Assigning value 10 to a 
    // using "=" operator 
    int a = 10; 
    cout << "Value of a is "<


输出:
Value of a is 10
Value of a is 20
Value of a is 10
Value of a is 100
Value of a is 10
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。