Why does the write method take a character pointer to the object one wishes to write?

Discussion in 'C++' started by AMT2K5, Dec 10, 2005.

  1. AMT2K5

    AMT2K5 Guest

    Would it not be more efficient to take in a void pointer?

    int number = 30;
    fout.write((char *)(&number), sizeof(number));
    AMT2K5, Dec 10, 2005
    #1
    1. Advertising

  2. On 10 Dec 2005 10:40:14 -0800, "AMT2K5" <> wrote:

    >Would it not be more efficient to take in a void pointer?
    >
    >int number = 30;
    >fout.write((char *)(&number), sizeof(number));


    No. Why do you think it would be more efficient?

    --
    Bob Hairgrove
    Bob Hairgrove, Dec 10, 2005
    #2
    1. Advertising

  3. AMT2K5

    AMT2K5 Guest

    What purpose does it serve to cast as a character pointer?
    AMT2K5, Dec 10, 2005
    #3
  4. On 10 Dec 2005 10:48:36 -0800, "AMT2K5" <> wrote:

    >What purpose does it serve to cast as a character pointer?


    You are telling fout to write an int as binary data, so you must cast
    the address of your number to a char* and give the size so that the
    stream knows how many bytes (i.e. char's) to write.

    The problem with void* is that void is not a type. With char*, you
    know that you are dealing with a type which is exactly one byte large.
    And a pointer to an object can be implicitly converted to void*, so
    using char* is more type-safe. That is one of the major advantages of
    C++ over C, for example.

    But you still didn't say why you think void* would be more efficient?
    The cast doesn't cost any processor cycles, nor does it take up any
    extra memory.

    --
    Bob Hairgrove
    Bob Hairgrove, Dec 10, 2005
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Keith H Duggar
    Replies:
    6
    Views:
    325
    Attila Feher
    Jan 29, 2004
  2. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,739
    Smokey Grindel
    Dec 2, 2006
  3. dandelion

    [OT] Seasonal Best Wishes

    dandelion, Dec 24, 2004, in forum: C Programming
    Replies:
    0
    Views:
    293
    dandelion
    Dec 24, 2004
  4. Replies:
    12
    Views:
    497
    Skarmander
    Jun 24, 2006
  5. Satish Talim

    Best Wishes for 2008

    Satish Talim, Dec 30, 2007, in forum: Ruby
    Replies:
    0
    Views:
    86
    Satish Talim
    Dec 30, 2007
Loading...

Share This Page