Why are the outputs of printf and std::cout different?What is the difference between #include...

Why did the EU agree to delay the Brexit deadline?

How to write values with uncertainty and units with brackets: (339+-14) m/s

Is there any references on the tensor product of presentable (1-)categories?

What changes for testers when they are testing in agile environments?

Does Doodling or Improvising on the Piano Have Any Benefits?

copy and scale one figure (wheel)

Infinite dials to reset ever?

Basic combinatorial probability problem

Is preaching recommended or mandatory to a temple priest?

Is (0,1] a closed or open set?

What will be next at the bottom row and why?

Is this toilet slogan correct usage of the English language?

What is the evidence for the "tyranny of the majority problem" in a direct democracy context?

What does routing an IP address mean?

Did arcade monitors have same pixel aspect ratio as TV sets?

How to advoid Unknown field: MyJSON.number

Is Witten's Proof of the Positive Mass Theorem Rigorous?

Python scanner for the first free port in a range

Can disgust be a key component of horror?

Is there a RAID 0 Equivalent for RAM?

Count the occurrence of each unique word in the file

Does a 'pending' US visa application constitute a denial?

Evaluating expression with Integer part and Fraction part of a nested radical

Does collectivism actually exist?



Why are the outputs of printf and std::cout different?


What is the difference between #include <filename> and #include “filename”?What are the differences between a pointer variable and a reference variable in C++?Why can templates only be implemented in the header file?Why is “using namespace std” considered bad practice?C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Why are elementwise additions much faster in separate loops than in a combined loop?Why is it faster to process a sorted array than an unsorted array?Why does this output of the same expression from printf differ from cout?file descriptors, difference between printf and std::coutC++ difference in behavior between cout and printf













38















I tried the following code of C++. However, the outputs of printf and std::cout are different. Why?



struct Foo
{
int a;
int b;
int c;
};

int main()
{
printf("%dn", &Foo::c); // The output is 8
std::cout << &Foo::c << "n"; // The output is 1
}









share|improve this question




















  • 24





    main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

    – YesThatIsMyName
    Mar 14 at 11:30











  • @Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

    – Pete Becker
    Mar 15 at 12:30
















38















I tried the following code of C++. However, the outputs of printf and std::cout are different. Why?



struct Foo
{
int a;
int b;
int c;
};

int main()
{
printf("%dn", &Foo::c); // The output is 8
std::cout << &Foo::c << "n"; // The output is 1
}









share|improve this question




















  • 24





    main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

    – YesThatIsMyName
    Mar 14 at 11:30











  • @Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

    – Pete Becker
    Mar 15 at 12:30














38












38








38


3






I tried the following code of C++. However, the outputs of printf and std::cout are different. Why?



struct Foo
{
int a;
int b;
int c;
};

int main()
{
printf("%dn", &Foo::c); // The output is 8
std::cout << &Foo::c << "n"; // The output is 1
}









share|improve this question
















I tried the following code of C++. However, the outputs of printf and std::cout are different. Why?



struct Foo
{
int a;
int b;
int c;
};

int main()
{
printf("%dn", &Foo::c); // The output is 8
std::cout << &Foo::c << "n"; // The output is 1
}






c++






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 18 at 19:17









Peter Mortensen

13.8k1987113




13.8k1987113










asked Mar 14 at 11:19









uu dduu dd

20825




20825








  • 24





    main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

    – YesThatIsMyName
    Mar 14 at 11:30











  • @Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

    – Pete Becker
    Mar 15 at 12:30














  • 24





    main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

    – YesThatIsMyName
    Mar 14 at 11:30











  • @Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

    – Pete Becker
    Mar 15 at 12:30








24




24





main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

– YesThatIsMyName
Mar 14 at 11:30





main.cpp:22:27: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int Foo::*’ [-Wformat=]

– YesThatIsMyName
Mar 14 at 11:30













@Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

– Pete Becker
Mar 15 at 12:30





@Angew -- I was replying to a comment that has now been deleted. It said that Foo::c hadn't been initialized.

– Pete Becker
Mar 15 at 12:30












3 Answers
3






active

oldest

votes


















73














printf("%dn", &Foo::c): this is undefined behavior, as &Foo::c is not an integer, but a pointer to member (but, actually, it is usual that the compiler stores pointer to data member as offset, and as 8 is the offset of Foo::c, 8 is printed).



std::cout << &Foo::c: this prints the value &Foo::c. As iostream doesn't have a pointer to member printer, it chooses the closest one: it converts it to bool, and prints it as integer. As &Foo::c converted to bool is true, 1 is printed.






share|improve this answer


























  • You know member-pointers have to take into account the possibility of virtual inheritance?

    – Deduplicator
    Mar 14 at 12:50








  • 1





    @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

    – MSalters
    Mar 14 at 12:57






  • 1





    @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

    – Deduplicator
    Mar 14 at 13:00








  • 4





    @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

    – StoryTeller
    Mar 14 at 13:07








  • 2





    @StoryTeller: and yet we have std::is_member_pointer :)

    – geza
    Mar 14 at 13:26



















20














The output is different because the behavior of your printf is undefined.



A pointer to member (like the one produced from &Foo::c) is not an integer. The printf function expects an integer, since you told it too with the %d specifier.



You can amend it by adding a cast to bool, like this:



printf("%dn", (bool)&Foo::c)


A pointer to member may be converted to a bool (which you do with the cast), and the bool then undergoes integral promotion to an int on account of being an integral variadic argument to a variadic function.



Speaking of the conversion to bool, it's exactly the conversion that is applied implicitly by attempting to call std::ostream's operator<<. Since there isn't an overload of the operator that supports pointers to members, overload resolution selects another that is callable after implicitly converting &Foo::c to a boolean.






share|improve this answer

































    4














    In addition to the more literal answer about why the compiler interpreted your code the way it did: you seem to have an XY problem You’re trying to format a pointer-to-member as an integer, which strongly suggests you meant to do something different.



    If what you wanted was an int value stored in .c, you either need to create an instance Foo some_foo; and take some_foo.c, or else you need to declare Foo::c a static member, so there’s one unambiguous Foo::c across the entire class. Do not take the address in this case.



    If what you wanted was to take an address of the .c member of some Foo, you should do as above so that Foo::c is static and refers to one specific variable, or else declare an instance and take its .c member, then take the address. The correct printf() specifier for an object pointer is %p, and to print an object pointer representation with <iostream>, convert it to void*:



    printf( "%pn", &some_foo.c );
    std::cout << static_cast<void*>{&some_foo.c} << 'n';


    If what you want is the offset of Foo::c within class Foo, you want the offsetof() macro in <stddef.h>. Since its return value is size_t, which is not the same size as int on 64-bit platforms, you would want to either cast the result explicitly or pass printf() the z type specifier:



    #include <stddef.h>

    /* ... */

    constexpr size_t offset_c = offsetof( Foo, c );
    printf( "%zun", offset_c );
    cout << offset_c << 'n';


    Whatever you were trying to do, if your compiler didn’t warn you about the type mismatch, you ought to turn on more warnings. This is especially true for someone coding by trial and error until the program compiles.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55161182%2fwhy-are-the-outputs-of-printf-and-stdcout-different%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      73














      printf("%dn", &Foo::c): this is undefined behavior, as &Foo::c is not an integer, but a pointer to member (but, actually, it is usual that the compiler stores pointer to data member as offset, and as 8 is the offset of Foo::c, 8 is printed).



      std::cout << &Foo::c: this prints the value &Foo::c. As iostream doesn't have a pointer to member printer, it chooses the closest one: it converts it to bool, and prints it as integer. As &Foo::c converted to bool is true, 1 is printed.






      share|improve this answer


























      • You know member-pointers have to take into account the possibility of virtual inheritance?

        – Deduplicator
        Mar 14 at 12:50








      • 1





        @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

        – MSalters
        Mar 14 at 12:57






      • 1





        @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

        – Deduplicator
        Mar 14 at 13:00








      • 4





        @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

        – StoryTeller
        Mar 14 at 13:07








      • 2





        @StoryTeller: and yet we have std::is_member_pointer :)

        – geza
        Mar 14 at 13:26
















      73














      printf("%dn", &Foo::c): this is undefined behavior, as &Foo::c is not an integer, but a pointer to member (but, actually, it is usual that the compiler stores pointer to data member as offset, and as 8 is the offset of Foo::c, 8 is printed).



      std::cout << &Foo::c: this prints the value &Foo::c. As iostream doesn't have a pointer to member printer, it chooses the closest one: it converts it to bool, and prints it as integer. As &Foo::c converted to bool is true, 1 is printed.






      share|improve this answer


























      • You know member-pointers have to take into account the possibility of virtual inheritance?

        – Deduplicator
        Mar 14 at 12:50








      • 1





        @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

        – MSalters
        Mar 14 at 12:57






      • 1





        @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

        – Deduplicator
        Mar 14 at 13:00








      • 4





        @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

        – StoryTeller
        Mar 14 at 13:07








      • 2





        @StoryTeller: and yet we have std::is_member_pointer :)

        – geza
        Mar 14 at 13:26














      73












      73








      73







      printf("%dn", &Foo::c): this is undefined behavior, as &Foo::c is not an integer, but a pointer to member (but, actually, it is usual that the compiler stores pointer to data member as offset, and as 8 is the offset of Foo::c, 8 is printed).



      std::cout << &Foo::c: this prints the value &Foo::c. As iostream doesn't have a pointer to member printer, it chooses the closest one: it converts it to bool, and prints it as integer. As &Foo::c converted to bool is true, 1 is printed.






      share|improve this answer















      printf("%dn", &Foo::c): this is undefined behavior, as &Foo::c is not an integer, but a pointer to member (but, actually, it is usual that the compiler stores pointer to data member as offset, and as 8 is the offset of Foo::c, 8 is printed).



      std::cout << &Foo::c: this prints the value &Foo::c. As iostream doesn't have a pointer to member printer, it chooses the closest one: it converts it to bool, and prints it as integer. As &Foo::c converted to bool is true, 1 is printed.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 14 at 13:38

























      answered Mar 14 at 11:31









      gezageza

      13.7k33178




      13.7k33178













      • You know member-pointers have to take into account the possibility of virtual inheritance?

        – Deduplicator
        Mar 14 at 12:50








      • 1





        @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

        – MSalters
        Mar 14 at 12:57






      • 1





        @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

        – Deduplicator
        Mar 14 at 13:00








      • 4





        @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

        – StoryTeller
        Mar 14 at 13:07








      • 2





        @StoryTeller: and yet we have std::is_member_pointer :)

        – geza
        Mar 14 at 13:26



















      • You know member-pointers have to take into account the possibility of virtual inheritance?

        – Deduplicator
        Mar 14 at 12:50








      • 1





        @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

        – MSalters
        Mar 14 at 12:57






      • 1





        @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

        – Deduplicator
        Mar 14 at 13:00








      • 4





        @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

        – StoryTeller
        Mar 14 at 13:07








      • 2





        @StoryTeller: and yet we have std::is_member_pointer :)

        – geza
        Mar 14 at 13:26

















      You know member-pointers have to take into account the possibility of virtual inheritance?

      – Deduplicator
      Mar 14 at 12:50







      You know member-pointers have to take into account the possibility of virtual inheritance?

      – Deduplicator
      Mar 14 at 12:50






      1




      1





      @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

      – MSalters
      Mar 14 at 12:57





      @Deduplicator: Only for classes that use virtual inheritance, of course. There's no member pointer equivalent of void*, each class has its own unique types of member pointers. Even sizeof(int Foo::*) may depend on Foo.

      – MSalters
      Mar 14 at 12:57




      1




      1





      @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

      – Deduplicator
      Mar 14 at 13:00







      @MSalters No. You can have and use a int Foo::* perfectly fine while Foo is still incomplete and in no danger of being completed anytime soon. Admittedly, MS especially likes to play fast and loose with member-pointers of any kind.

      – Deduplicator
      Mar 14 at 13:00






      4




      4





      @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

      – StoryTeller
      Mar 14 at 13:07







      @all - I held my peace until now, but can we stop with the "member-pointer" business? The term is "pointer-to-member". And when it comes to technical terms, it matters. Just as "chocolate milk" isn't the same as "milk chocolate". </pedantry>

      – StoryTeller
      Mar 14 at 13:07






      2




      2





      @StoryTeller: and yet we have std::is_member_pointer :)

      – geza
      Mar 14 at 13:26





      @StoryTeller: and yet we have std::is_member_pointer :)

      – geza
      Mar 14 at 13:26













      20














      The output is different because the behavior of your printf is undefined.



      A pointer to member (like the one produced from &Foo::c) is not an integer. The printf function expects an integer, since you told it too with the %d specifier.



      You can amend it by adding a cast to bool, like this:



      printf("%dn", (bool)&Foo::c)


      A pointer to member may be converted to a bool (which you do with the cast), and the bool then undergoes integral promotion to an int on account of being an integral variadic argument to a variadic function.



      Speaking of the conversion to bool, it's exactly the conversion that is applied implicitly by attempting to call std::ostream's operator<<. Since there isn't an overload of the operator that supports pointers to members, overload resolution selects another that is callable after implicitly converting &Foo::c to a boolean.






      share|improve this answer






























        20














        The output is different because the behavior of your printf is undefined.



        A pointer to member (like the one produced from &Foo::c) is not an integer. The printf function expects an integer, since you told it too with the %d specifier.



        You can amend it by adding a cast to bool, like this:



        printf("%dn", (bool)&Foo::c)


        A pointer to member may be converted to a bool (which you do with the cast), and the bool then undergoes integral promotion to an int on account of being an integral variadic argument to a variadic function.



        Speaking of the conversion to bool, it's exactly the conversion that is applied implicitly by attempting to call std::ostream's operator<<. Since there isn't an overload of the operator that supports pointers to members, overload resolution selects another that is callable after implicitly converting &Foo::c to a boolean.






        share|improve this answer




























          20












          20








          20







          The output is different because the behavior of your printf is undefined.



          A pointer to member (like the one produced from &Foo::c) is not an integer. The printf function expects an integer, since you told it too with the %d specifier.



          You can amend it by adding a cast to bool, like this:



          printf("%dn", (bool)&Foo::c)


          A pointer to member may be converted to a bool (which you do with the cast), and the bool then undergoes integral promotion to an int on account of being an integral variadic argument to a variadic function.



          Speaking of the conversion to bool, it's exactly the conversion that is applied implicitly by attempting to call std::ostream's operator<<. Since there isn't an overload of the operator that supports pointers to members, overload resolution selects another that is callable after implicitly converting &Foo::c to a boolean.






          share|improve this answer















          The output is different because the behavior of your printf is undefined.



          A pointer to member (like the one produced from &Foo::c) is not an integer. The printf function expects an integer, since you told it too with the %d specifier.



          You can amend it by adding a cast to bool, like this:



          printf("%dn", (bool)&Foo::c)


          A pointer to member may be converted to a bool (which you do with the cast), and the bool then undergoes integral promotion to an int on account of being an integral variadic argument to a variadic function.



          Speaking of the conversion to bool, it's exactly the conversion that is applied implicitly by attempting to call std::ostream's operator<<. Since there isn't an overload of the operator that supports pointers to members, overload resolution selects another that is callable after implicitly converting &Foo::c to a boolean.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 14 at 13:05

























          answered Mar 14 at 11:31









          StoryTellerStoryTeller

          103k12216280




          103k12216280























              4














              In addition to the more literal answer about why the compiler interpreted your code the way it did: you seem to have an XY problem You’re trying to format a pointer-to-member as an integer, which strongly suggests you meant to do something different.



              If what you wanted was an int value stored in .c, you either need to create an instance Foo some_foo; and take some_foo.c, or else you need to declare Foo::c a static member, so there’s one unambiguous Foo::c across the entire class. Do not take the address in this case.



              If what you wanted was to take an address of the .c member of some Foo, you should do as above so that Foo::c is static and refers to one specific variable, or else declare an instance and take its .c member, then take the address. The correct printf() specifier for an object pointer is %p, and to print an object pointer representation with <iostream>, convert it to void*:



              printf( "%pn", &some_foo.c );
              std::cout << static_cast<void*>{&some_foo.c} << 'n';


              If what you want is the offset of Foo::c within class Foo, you want the offsetof() macro in <stddef.h>. Since its return value is size_t, which is not the same size as int on 64-bit platforms, you would want to either cast the result explicitly or pass printf() the z type specifier:



              #include <stddef.h>

              /* ... */

              constexpr size_t offset_c = offsetof( Foo, c );
              printf( "%zun", offset_c );
              cout << offset_c << 'n';


              Whatever you were trying to do, if your compiler didn’t warn you about the type mismatch, you ought to turn on more warnings. This is especially true for someone coding by trial and error until the program compiles.






              share|improve this answer




























                4














                In addition to the more literal answer about why the compiler interpreted your code the way it did: you seem to have an XY problem You’re trying to format a pointer-to-member as an integer, which strongly suggests you meant to do something different.



                If what you wanted was an int value stored in .c, you either need to create an instance Foo some_foo; and take some_foo.c, or else you need to declare Foo::c a static member, so there’s one unambiguous Foo::c across the entire class. Do not take the address in this case.



                If what you wanted was to take an address of the .c member of some Foo, you should do as above so that Foo::c is static and refers to one specific variable, or else declare an instance and take its .c member, then take the address. The correct printf() specifier for an object pointer is %p, and to print an object pointer representation with <iostream>, convert it to void*:



                printf( "%pn", &some_foo.c );
                std::cout << static_cast<void*>{&some_foo.c} << 'n';


                If what you want is the offset of Foo::c within class Foo, you want the offsetof() macro in <stddef.h>. Since its return value is size_t, which is not the same size as int on 64-bit platforms, you would want to either cast the result explicitly or pass printf() the z type specifier:



                #include <stddef.h>

                /* ... */

                constexpr size_t offset_c = offsetof( Foo, c );
                printf( "%zun", offset_c );
                cout << offset_c << 'n';


                Whatever you were trying to do, if your compiler didn’t warn you about the type mismatch, you ought to turn on more warnings. This is especially true for someone coding by trial and error until the program compiles.






                share|improve this answer


























                  4












                  4








                  4







                  In addition to the more literal answer about why the compiler interpreted your code the way it did: you seem to have an XY problem You’re trying to format a pointer-to-member as an integer, which strongly suggests you meant to do something different.



                  If what you wanted was an int value stored in .c, you either need to create an instance Foo some_foo; and take some_foo.c, or else you need to declare Foo::c a static member, so there’s one unambiguous Foo::c across the entire class. Do not take the address in this case.



                  If what you wanted was to take an address of the .c member of some Foo, you should do as above so that Foo::c is static and refers to one specific variable, or else declare an instance and take its .c member, then take the address. The correct printf() specifier for an object pointer is %p, and to print an object pointer representation with <iostream>, convert it to void*:



                  printf( "%pn", &some_foo.c );
                  std::cout << static_cast<void*>{&some_foo.c} << 'n';


                  If what you want is the offset of Foo::c within class Foo, you want the offsetof() macro in <stddef.h>. Since its return value is size_t, which is not the same size as int on 64-bit platforms, you would want to either cast the result explicitly or pass printf() the z type specifier:



                  #include <stddef.h>

                  /* ... */

                  constexpr size_t offset_c = offsetof( Foo, c );
                  printf( "%zun", offset_c );
                  cout << offset_c << 'n';


                  Whatever you were trying to do, if your compiler didn’t warn you about the type mismatch, you ought to turn on more warnings. This is especially true for someone coding by trial and error until the program compiles.






                  share|improve this answer













                  In addition to the more literal answer about why the compiler interpreted your code the way it did: you seem to have an XY problem You’re trying to format a pointer-to-member as an integer, which strongly suggests you meant to do something different.



                  If what you wanted was an int value stored in .c, you either need to create an instance Foo some_foo; and take some_foo.c, or else you need to declare Foo::c a static member, so there’s one unambiguous Foo::c across the entire class. Do not take the address in this case.



                  If what you wanted was to take an address of the .c member of some Foo, you should do as above so that Foo::c is static and refers to one specific variable, or else declare an instance and take its .c member, then take the address. The correct printf() specifier for an object pointer is %p, and to print an object pointer representation with <iostream>, convert it to void*:



                  printf( "%pn", &some_foo.c );
                  std::cout << static_cast<void*>{&some_foo.c} << 'n';


                  If what you want is the offset of Foo::c within class Foo, you want the offsetof() macro in <stddef.h>. Since its return value is size_t, which is not the same size as int on 64-bit platforms, you would want to either cast the result explicitly or pass printf() the z type specifier:



                  #include <stddef.h>

                  /* ... */

                  constexpr size_t offset_c = offsetof( Foo, c );
                  printf( "%zun", offset_c );
                  cout << offset_c << 'n';


                  Whatever you were trying to do, if your compiler didn’t warn you about the type mismatch, you ought to turn on more warnings. This is especially true for someone coding by trial and error until the program compiles.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 14 at 16:55









                  DavislorDavislor

                  8,98511227




                  8,98511227






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55161182%2fwhy-are-the-outputs-of-printf-and-stdcout-different%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

                      Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

                      Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...