【问题标题】:How can you use compound assignment operators in C if you can't redefine variables?如果不能重新定义变量,如何在 C 中使用复合赋值运算符?
【发布时间】:2020-10-20 03:20:16
【问题描述】:

看着wikipedia 它说:

a -= b;

相同
a = a - b;

但是当我在我的 C 程序中尝试这个时,我得到了以下错误:

"error: redefinition of 'a'".

这是我的程序:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a = 10;
    int a -= 5;

    printf("a has a value of %d\n", a);

    return 0;
}

我收到以下错误:

my_prog.c:6:6: error: redefinition of 'a'
       int a -= 5; 
           ^
my_prog.c:5:6: note: previous definition is here
       int a = 10;
           ^
my_prog.c:6:8: error: invalid '-=' at end of declaration; did you mean >'='?
       int a -= 5; 
             ^~

我在 Mac 上使用 clang。

【问题讨论】:

  • 缺少分号。
  • 在上下文方面我已经添加了我的代码,我认为标题很清楚。
  • int a.... 是一个定义。但是你已经定义了它。你想要一个表达式。删除int
  • 标题对 R 程序员来说很清楚,因为在 R 中,赋值 一个定义。在 C 中,赋值语句会更改现有变量的值。它不会创建新变量,也不能用于更改现有变量的类型。

标签: c redefinition compound-assignment


【解决方案1】:

int a = 10 是一个定义。

它将变量名称和类型的声明 (int a) 与其初始化 (a = 10) 结合在一起。

该语言不允许对同一个变量进行多次定义,但它允许使用赋值运算符(a = 10a = a - b
a -= b 等)多次更改变量的值。

你的代码应该是:

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a = 10;    // declare variable `a` of type `int` and initialize it with 10
    a -= 5;        // subtract 5 from the value of `a` and store the result in `a`

    printf("a has a value of %d\n", a);

    return 0;
}

【讨论】:

  • 你可能是对的。这十年我没有写过 C 代码,我把它们混在一起了 :-(
【解决方案2】:

a 的定义如下:

int a;

a 的初始化如下:

a = 10;

你在同一个表达式中做这两个:

int a = 10;

现在a 已定义并初始化。

如果您执行以下操作:

int a -= 5;

在前面的表达式之后,您正在重新定义a,因此出现错误。

你只需要:

a -= 5;

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 2020-03-23
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多