Thread: winky dink

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    39

    winky dink

    If I create a dummy struct to copy one array in two an other does that mean I am saving time by avoiding a for loop. For example:
    Code:
    //then I create 
    struct { int x[100];} dummy_array100  {1,2,3,........,100};
    struct dummy_array50 { int y[50];};
    
    dummy_array50 = dummy_array100;
    copy the first 50 elements in to the new array. I guess the compiler does the loop for me.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The structs have to be the same type for struct assignment to work.

    And no, it doesn't save a huge amount of time, there will almost certainly be a loop somewhere.

    Search the board for "premature optimisation".
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    You can't just arbitrarily assign two different struct types to eachother. If you tried to implement your code, you would have found that out quite quickly. The compiler wouldn't even compile that code. Now, if you assigned one dummy_array50 to another dummy_array50, the compiler would "do the loop for you". It would generate some sort of code to copy the structures, but honestly, the it probably just calls memcpy under the hood. Now, memcpy has a loop built in, but it's highly optimized, so it will be about as quick as you can get, and you just don't need to worry about it. In short, if you have to copy one struct to another, and they're both the same type, use an = sign. If they're two different structs, you have to write the copy yourself.

    All this talk of saving time makes me think you're interested in optimizing something that probably doesn't need optimizing yet. Remember, pre-optimization is the root of all evil. Don't even try to speed up your code until you know it's way too slow.

    EDIT: Salem beat me to it!

Popular pages Recent additions subscribe to a feed