Struct assignment (Just a tip)

    Both standard C and Standard C++ support struct assignment using = . In fact, C++ programmers are often surprised to discover that assignment operator applies also to plain structs, and not just to objects, and C programmers are even more puzzled to discover they don’t have to assign structs tediously, field-by-field when they have a much better alternative:

        9.2: I heard that structures could be assigned to variables and passed to and from functions, but K&R I says not.

What K&R I said was that the restrictions on struct operations would be lifted in a forthcoming version of the compiler, and in fact struct assignment and passing were fully functional in Ritchie's compiler even as K&R I was being published.  Although a few early C compilers lacked struct assignment, all modern compilers support it, and it is part of the ANSI C standard, so there should be no reluctance to use it.

 

Yes, structure assignment is fine. But if you have pointers in the struct,
you might need to make copies of the data pointed to (a so-called "deep
copy"). (An alternative is reference counting, but that's a bit more
complicated.)

 

so, feel free to use "=" when assigning structs.

posted @ 2011-12-09 11:35  英超  Views(313)  Comments(0Edit  收藏  举报