C Programming: Structure Assignment

這篇文章主要是記錄自己的孤陋寡聞 ...

今天同事在聊一段程式碼(內容就不多講了,反正簡化後如下)。乍看之下大吃一驚,為什麼Structure 間可以直接使用 Assignment?在我過去的認知裡面,如果要對 Structure 作拷貝的動作,應該要使用 memcpy 才對吧?所以才寫了小小的程式碼測試一下。

#include <stdio.h>
#include <stdlib.h>

struct tObj
{
    int a;
    double b;
    int c[3];
};

int main()
{
    struct tObj obj1;
    struct tObj obj2;
    
    obj1.a = 1;
    obj1.b = 2.0;
    obj1.c[0] = 3;
    obj1.c[1] = 4;
    obj1.c[2] = 5;
    
    obj2.a = 0;
    obj2.b = 0.0;
    obj2.c[0] = 0;
    obj2.c[1] = 0;
    obj2.c[2] = 0;
    
    obj2 = obj1;
    
    printf( "obj2.a = %d\n", obj2.a );
    printf( "obj2.b = %f\n", obj2.b );
    printf( "obj2.c[0] = %d\n", obj2.c[0] );
    printf( "obj2.c[1] = %d\n", obj2.c[1] );
    printf( "obj2.c[2] = %d\n", obj2.c[2] );
    
    return 0;
}
那麼,這個程式的 Output 是?(上面都那樣寫了,應該每個人都知道了吧)

附上 C99 的資料:

6.5.16.1 Simple assignment Constraints
One of the following shall hold:

  • the left operand has qualified or unqualified arithmetic type and the right has arithmetic type;
  • the left operand has a qualified or unqualified version of a structure or union type compatible with the type of the right;
  • both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • the left operand is a pointer and the right is a null pointer constant; or
  • the left operand has type _Bool and the right is a pointer.

留言

這個網誌中的熱門文章

我弟家的新居感恩禮拜分享:善頌善禱

如何將Linux打造成OpenFlow Switch:Openvswitch

Openssl 範例程式:建立SSL連線