What is the difference between "String" and &"String"



  • As far as I know, expression like "String" is automatically converted to the pointer to that string in memory. But &"String" is also a pointer. What it the difference?



  • this is a german forum...

    Bitte kann ein Mod den Post in ein anderes Forum verschieben, z.B. nach http://cplusplus.com/forum/?
    😃



  • "String" is an object of type const char[7] , so obviously &"String" should be a pointer to this object (and have type const char (*)[7] , "pointer to const char[7]"). I haven't checked, but if this is valid syntax, it's the only sensible interpretation 😉



  • Bashar schrieb:

    I haven't checked, but if this is valid syntax, it's the only sensible interpretation 😉

    It is valid and your explanation is also right.



  • Yes, I also found this myself.

    But what is the difference between the array and pointer_to_array, except that they formally have different types? I have found in the debugger that they have equal values (the array name is threated as pointer to the first array element, and pointer to the array also points to the same adress).


  • Mod

    SAn schrieb:

    As far as I know, expression like "String" is automatically converted to the pointer to that string in memory.

    not quite. An array expression can decay to a pointer to the first element of that array - that is the array-to-pointer standard conversion. Conversely, the unary & operator yields a pointer that points to the argument - that is the whole array - no just a part of it. Naturally, given the semantics of pointer arithmetic and array layout, it is easily possible with just a pointer to a single element to reach every other element as well.
    This array-to-pointer standard conversion happens quite often, because very few operators take array arguments (that would be unary & and siezof) as opposed to rvalue pointer operands. Arrays cannot be function arguments so except in the case of binding to a reference array decay is frequently seen there too.



  • So, if I correctly understand you, the answer is:
    «The "String" is not automatically converted to the pointer to its first element in &"String" expression, because the & operator can take array parameter.»


  • Mod

    SAn schrieb:

    So, if I correctly understand you, the answer is:
    «The "String" is not automatically converted to the pointer to its first element in &"String" expression, because the & operator can take array parameter.»

    quite so. in addition the unary & operator doesn't take rvalue-arguments, so the array-to-pointer conversion couldn't possibly help: without & being able to take l-value arrays the expression &"foo" would simply be ill-formed.


Log in to reply