2014-02-06 80 views
-6

如何修復以下程序的c編譯器錯誤?C有不同的數據類型嗎?

struct a{ 
     int a; 
}; 
struct b{ 
    int b; 
}; 
int main(){ 

int toggle =1; 
int y = (toggle==1) && (struct a x); 
y =  (toggle==0) && (struct b x); 

if(toggle==1){ 
    x.a = 10; 
    printf("%d ",x.a); 
}else { 
    x.b = 20; 
    printf("%d ",x.b); 
} 
printf("hi"); 
return 0; 
} 

當我編譯這個程序我「之前,‘X’預期‘)’」

得到錯誤,我需要創建靜態對象。還有其他方法可以實現嗎?

+2

什麼是'x'?事實上,int y =(toggle == 1)&&(struct a x); y =(toggle == 0)&&(struct b x); x t;'是什麼意思? – haccks

回答

3

您不能將聲明作爲表達式的一部分。您需要找出處理條件編譯/聲明的另一種方法(可能使用預處理器?)。


一種可能的方式可以是具有共同的基礎結構,與「切換」作爲它的標誌,並且使用指針此基礎結構型播到正確的結構。可以這麼說,C中的「inhearitance」很軟。類似於

enum Type 
{ 
    TYPE_A, 
    TYPE_B 
}; 

struct Base 
{ 
    int type; /* One of the Type enumerations */ 
}; 

struct A 
{ 
    struct Base base; 
    int field_unique_to_a; 
}; 

struct B 
{ 
    struct Base base; 
    double field_unique_to_b; 
}; 

int main(void) 
{ 
    int toggle = 1; 
    struct Base *base_ptr; 

    if (toggle == 1) 
    { 
     base_ptr = calloc(1, sizeof(A)); /* Use calloc to initialize the data */ 
     base_ptr->type = TYPE_A; 
    } 
    else 
    { 
     base_ptr = calloc(1, sizeof(B)); /* Use calloc to initialize the data */ 
     base_ptr->type = TYPE_B; 
    } 

    /* Now `base_ptr` points either to a `A` or a `B` structure */ 

    if (base_ptr->type == TYPE_A) 
    { 
     ((struct A *) base_ptr)->field_unique_to_a = 1; 
    } 
    else 
    { 
     ((struct B *) base_ptr)->field_unique_to_b = 12.34; 
    } 

    /* ... */ 
} 
相關問題