Naman Aggarwal
Naman Aggarwal

Reputation: 5

Why the following code block is giving output "ZZZ(some garbage value)" instead of "ZZ(some garbage value)"

On printing the &a (cout<<&a), compiler is giving output 'Z' but when we print character before printing character address it gives output(cout<<a<<" "<<&a) as 'Z ZZ'. I know that cout treats character address differently i.e on getting an address of character it doesn't print that address instead it prints the contents which are there at that address. Please help me with the concept i am missing here. Here is the code snippet:

#include <iostream>
using namespace std;
int main() {
    char a = 'Z';
    cout<<a<<&a;
    return 0;
}

Upvotes: 0

Views: 468

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

If you want to output the address of the variable a then write

char a = 'Z';
cout << a << static_cast<void *>( &a );

Otherwise the compiler tries to output a string pointed to by the expression &a that has the type char * until the zero-terminating character is encountered.

Thus this output

cout << &a;

has undefined behavior.

If you want to output the variable a as an array having a string then you have to declare an array instead of the scalar variable and initialize it with a string literal instead of the character literal. For example

char a[] = "Z";
cout << *a << &a;

Upvotes: 2

bolov
bolov

Reputation: 75727

char a = 'Z';
cout << &a;

This treats the address of a as an address to a null terminated string and prints this string. Since that is not a pointer to a null terminated string (it's a pointer to a single char) you have Undefined Behavior in your program.

Undefined Behavior means that the program doesn't have a defined behavior, i.e. it can have any behavior: it can print garbage, it can print other garbage, it can print nothing, it can crash or pretty much any behavior.

Upvotes: 4

Related Questions