Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is printing of a member pointer to an int defined

Suppose I have this code:

#include <iostream>

struct Mine
{
    int a;
    int b;
};


int main()
{

    int Mine::* memberPointerA = &Mine::a;
    int Mine::* memberPointerB = &Mine::b;



    std::cout << memberPointerA;
    std::cout << "\n";
    std::cout << memberPointerB;
}

When I run this with Microsoft Visual C++ (2015)

I get the following output

1
1

The output I expect is something more like this:

1
2

So this begs the question: Is this printing of a member pointer defined behavior?

like image 646
DarthRubik Avatar asked Jul 27 '17 23:07

DarthRubik


People also ask

How do I print the content of a pointer?

Printing pointers. You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

How do you print the address of a pointer in C++?

How do I print the address stored in the pointer in C++? int *ptr = &var; printf("%p", ptr); That will print the address stored in ptr will be printed.

Does a pointer have an address?

The main feature of a pointer is its two-part nature. The pointer itself holds an address. The pointer also points to a value of a specific type - the value at the address the point holds.


1 Answers

There's a defined conversion from pointer to bool. Since the member variable pointers are not NULL, they evaluate as true and print as 1.

like image 191
1201ProgramAlarm Avatar answered Sep 22 '22 12:09

1201ProgramAlarm