Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this code compiles but doesnt show output when it runs (c++) in visual studio 2015 community

Tags:

c++

#include <conio.h>  // include conio.h file
#include <iostream.h> // or #include<iostream>

int main()
{
    int cout = 5;   
    cout << cout;

    return 0;
}

Why does this happen ??

The code compiles correctly but it does not give expected output when it runs

This does not give the output 5 and all other stuff

It also does not give a warning.

like image 481
Dhruv Chouhan Avatar asked Feb 03 '26 07:02

Dhruv Chouhan


1 Answers

The following line declares an int that happens to be called cout (it is not the std::cout stream)

int cout = 5;

The << operator peforms a bit shift.

So

cout << cout;

is only performing a bit shift and not storing the result.


To clarify, have a look at the following program:

#include<iostream>

int main()
{
    int cout = 5;
    auto shiftedval = cout << cout;
    std::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    return 0;
}

It will output:

cout's value is 5, and the result of the bit shift is 160

What is happening behind the scenes is that operator<< has been overloaded to take an ostream on the left hand side.

By including iostream you get this function and the compiler will know what you mean if you have an ostream to the left of the << operator.

Without a library the << would just simply have been a bitwise shift operator.


Also note that if you had ill-advisedly included using namespace std; or using std::cout then cout would then mean ostream and << would trigger a call to the library operator<< function. If after adding the using declaration above you include another declaration of cout the newly declared name will hide the previous declaration and cout will now be considered an int again and we're back to the bit shift operator functionality being used.

Example:

#include<iostream>

using namespace std; // using std:: at global scope

int main()
{
    int cout = 5;
    auto shiftedval = cout << cout;

    //the following will not compile, cout is an int:
    cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    //but we can get the cout from the global scope and the following will compile
    ::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    return 0;
}
like image 80
wally Avatar answered Feb 05 '26 22:02

wally



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!