2014-02-06 45 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; 
    } 

    /* ... */ 
} 
相关问题