Skip to main content
gamedev.net
🔒 Locked

Confusion with structs

Started by antistuff Jan 4, 2003 at 11:10 PM 2 replies 450+ views
Original Post
antistuff
antistuff
Im using c, not c++. So i have a struct like this typedef struct { int a; int b; } foo; now i have this foo f1, f2; f1.a = 1; f1.b = 2; if i go like this f2 = f1; is it the same as doing this f2.a = f1.a f2.b = f1.b i would think it is, but it seems like f2 = f1 makes f2 point to f1. but f2 isnt a pointer. which behavior is right? does it copy the values, or somethign else?
Fruny
Fruny
f2 = f1;

is indeed exactly the same as

f2.a = f1.a
f2.b = f1.b

unless you have written a custom assignment operator.


[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
johnnie2
johnnie2
It''s a copy.

If you haven''t explicitly provided a copy constructor for that struct (which you can do, btw), the compiler automatically comes up with one. In this case, the members of the first struct would be copied to the members of the second struct.

RapscallionGL - arriving soon.
____________"Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C
spock
spock
quote:
Original post by johnnie2
If you haven''t explicitly provided a copy constructor for that struct (which you can do, btw)


No, not in C you can''t.

Struct assignment and memberwise assignment may not be exactly equivalent due to the possibility of padding between structure members. The former may copy everything including padding while memberwise assignment will never copy padding.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.