【问题标题】:Error in C code error: expression is not assignableC 代码错误中的错误:表达式不可分配
【发布时间】:2017-08-12 15:58:57
【问题描述】:

我正在编写一个假设打印出程序执行描述的函数。我的程序中的一个函数使用0 作为基数为 10 的数字转换的信号。

我希望我的程序有友好的输出,并告诉用户一个数字是否已转换为以 10 为底,而不是让程序说该数字是从以 0 为基础的转换。

当我尝试编译此代码时,我收到一条错误消息,上面写着“表达式不可分配”。

我正在使用 cc 编译器在命令行上编译

Apple LLVM 版本 7.3.0 (clang-703.0.29)

知道这个错误是什么意思以及如何纠正吗? 谢谢。

void foo( int base ){

    int theBase;

    base == 0 ? theBase = 10: theBase = base;

    printf("%s%d\n", "The base is ", theBase)
}

错误信息:

error: expression is not assignable base == 0 ? theBase = 10: theBase = base; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^

【问题讨论】:

  • 如果一个解决方案对您来说足够好,请将其标记为结束您问题的最佳答案。

标签: c compiler-errors expression variable-assignment cc


【解决方案1】:

因为你需要左值,它所属的位置,在表达式的左边,像这样

theBase = (base == 0) ? 10 : base;

注意编译器是如何考虑的

base == 0 ? theBase = 10 : theBase

就像那个表达式中的“lvalue”,因为运算符优先级。

ternary operator 是一个运算符,所以你不能用它来代替 if 语句。

【讨论】:

    【解决方案2】:

    你应该使用

    theBase = (base == 0 ? 10 : base);
    

    而不是

    base == 0 ? theBase = 10: theBase = base;
    

    【讨论】:

      【解决方案3】:

      你必须把括号括起来

      base == 0 ? (theBase = 10) : (theBase = base);
      

      其他优先事项是欺骗你。更好的是,使用惯用语法:

      theBase = base ? base : 10;
      

      【讨论】:

        【解决方案4】:

        你在这里做的是一个条件赋值。

        通常你可以这样做:

        if (base == 0)
            theBase = 10;
        else
            theBase = base;
        

        在这里您选择使用三元表达式。它确实有点像 if/else 结构,但确实不同。

        三元返回一个值,它不是根据条件执行代码。不,它根据条件返回一个值。

        所以在这里,你必须这样做:

        theBase = (base == 0 ? 10 : base);
        

        (括号不是必需的,但最好避免错误)。

        事实上,你可以让三元代码以多种方式执行,比如返回一个函数:

        int my_function()
        {
            printf("Code executed\n");
            return (10);
        }
        
        /* ... */
        
        theBase = (base == 0 ? my_function() : base);
        

        编辑:

        是的,您可以使用该代码:

        base == 0 ? (theBase = 10) : (theBase = base);
        

        但在这种情况下使用三元组是毫无用处的,因为您仍然需要复制 theBase = X 代码。

        【讨论】:

        • 嗯,我真的很感动,我学三元表达式的方法很错误,谢谢你提供这些信息。
        【解决方案5】:

        不回答问题,但可能对遇到此问题的其他人有所帮助: 就我而言,我有法律任务,例如:

        int xyz = 5;
        

        我不知道包含的标题中的某处有以下行:

        #define xyz 14
        

        我不确定为什么编译器没有在这个语义错误之前大喊语法错误。无论哪种方式,如果有人感到沮丧以至于无法得出这个答案,我建议您检查变量名称之前是否尚未在某个地方定义为宏或类似名称。

        【讨论】:

          猜你喜欢
          • 2021-08-04
          • 2017-03-10
          • 2020-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多