2017-03-21 94 views
0

我正在写一个函数,用于打印出程序执行的描述。我的程序中的函数使用0作为基数为10的数字转换的信号。C代码错误中的错误:表达式不可赋值

,我想我的程序有友好的输出,并告诉用户如果一个已被转换为10进制,而不是让节目说数字从0为基数

转换当我尝试编译此代码,我收到一条错误消息,其中说'表达式不可分配'。

我编译命令行上用cc编译

苹果LLVM版本7.3.0(铛-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; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^

+0

如果有一种解决方案足够好,可以将其标记为解决您问题的最佳答案。 – Ludonope

回答

1

你在这里做什么是一个条件分配。

通常你可以那样做:

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

在这里,您chosed使用三元表达式。它确实有点像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的代码。

1

因为你需要的左值,它所属,在表达式的左侧,这样

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

注意如何编译器认为

base == 0 ? theBase = 10 : theBase 

类似于该表达式中的“左值”,这是因为运算符的优先级。

ternary operator,是,一个运营商,所以你不能用它来代替如果声明。

0

,您应该使用的

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

代替

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

你必须把括号围绕分配

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

其他优先捉弄你。更好的是,使用惯用语法:

theBase = base ? base : 10;