Tony Abboud
Tony Abboud

Reputation: 2430

No output in c++ program for big_endian check

I was experimenting with C++ and I decided to try the is_big_endian code, in much the same way I would do it in C. However I am getting no output when I try to print out the value of the pointer. I tried both the C and C++ style casts. What am I doing wrong?

#include <iostream>

using namespace std;

int main (void){
    int num = 1;
    char *ptr = (char *)&num;
    //char *ptr = reinterpret_cast<char *>(&num);

    cout << "Value is: " << *ptr << endl;
}

Upvotes: 0

Views: 42

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126867

operator<< sees that you are outputting a char, so it prints it as a character, not as a number (it's as if in C you wrote %c instead of %d in a printf); and since *ptr will either be 0 or 1, you'll end up in both cases with a non-printable character.

To fix this, cast explicitly *ptr to int:

cout << "Value is: " << int(*ptr) << endl;

Upvotes: 5

Related Questions