CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: Is the & operator intelligent

  1. #1
    Join Date
    Aug 2003
    Location
    NY
    Posts
    20

    Is the & operator intelligent

    Take a look at the code below:

    char foo[256] ;

    void Bar (void *) ;

    Now calling the function Bar as:

    Bar (foo) ; and
    Bar ((void*)&foo) ;

    why the two calls work the same? Is the & operator intelligent?

  2. #2
    Join Date
    Jun 2002
    Location
    Stockholm, Sweden
    Posts
    1,641
    No, but maybe the function is intelligent? Polymorphic?

    Or maybe your compiler happens to be "way too clever" :-)

    Did you check that it is not coincidence?

    / Z

  3. #3
    Join Date
    Nov 2003
    Posts
    74
    Actually, I believe that since char foo[256] can be used in place for a char* which can be converted to void*. The two functions would look like this when translated:

    Bar( foo ) = Bar( (char*) )

    Bar( (void*)&foo ) = Bar( (void*)&(char*) ) = Bar( (void*)(char**) )
    so you are actually passing it the pointer to the first element of the array of char's.

  4. #4
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    The compiler is able to implicitely convert any pointer to a pointer to void. It's in the standard.
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  5. #5
    Join Date
    Aug 2003
    Location
    NY
    Posts
    20
    Originally posted by Gabriel Fleseriu
    The compiler is able to implicitely convert any pointer to a pointer to void. It's in the standard.
    Its still not clear to me. Can somebody explain. I have debugged the code and I see that in both cases (foo and &foo), Bar () gets the same pointer.
    Had foo been an int, foo and &foo would mean two different things. In case of arrays, does the & operator has no meaning?

  6. #6
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128
    Originally posted by newbee240
    In case of arrays, does the & operator has no meaning?
    Yes, you are right. The following give the same results.

    Code:
    void Bar (void *) ;
    char foo[256] ;
    
    
    ...
    Bar(foo);
    Bar(&foo);
    Bar(&foo[0]);  // This is also the same unless you change the index

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)