2012-05-09 46 views
0

我想這個小代碼在IF語句中使用複合文字:複合文字

#include<stdio.h> 

struct time 
{ 
    int hour; 
    int minutes; 
    int seconds; 
}; 

int main(void) 
{ 
    struct time testTimes; 
    testTimes = (struct time){12,23,34}; 

    if (testTimes == (struct time){12,23,34}) 
     printf("%.2i:%.2i:%.2i\n", testTimes.hour, testTimes.minutes, testTimes.seconds); 
    else 
     printf("try again !\n"); 
    return 0; 
} 

它沒有工作。它提供了以下編譯信息:

prac.c:15:16: error: invalid operands to binary == (have ‘struct time’ and ‘struct time’)

是不是允許在IF語句中使用複合文字或語法不正確?

回答

3

有一個很好的理由,爲什麼你不能使用==操作

C FAQ

There is no good way for a compiler to implement structure comparison (i.e. to support the == operator for structures) which is consistent with C's low-level flavor. A simple byte-by-byte comparison could founder on random bits present in unused "holes" in the structure (such padding is used to keep the alignment of later fields correct). A field-by-field comparison might require unacceptable amounts of repetitive code for large structures. Any compiler-generated comparison could not be expected to compare pointer fields appropriately in all cases: for example, it's often appropriate to compare char * fields with strcmp rather than ==.

If you need to compare two structures, you'll have to write your own function to do so, field by field.

3

您無法使用==比較結構。

您應該分別比較結構的每個成員。

1

C提供無語言工具做結構

1

報價比較結構的==比較你不能比較結構。標準(C11 6.5.9 Equality operators)規定:

One of the following shall hold:
- both operands have arithmetic type;
- both operands are pointers to qualified or unqualified versions of compatible types;
- one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or
- one operand is a pointer and the other is a null pointer constant.

其中沒有適用於struct time,很遺憾。您需要單獨檢查字段==&&,或者有單獨的不變結構,您可以將其與memcmp進行比較。

雖然記住,後者建議很可能發生衝突的結構內的填充信息運行,因此前者可能是最好的選擇,除非你知道沒有填充。 。