2017-03-21 95 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;