C++ Why does this code compile? - c++

I'm trying to understand why does the following code compile?
#include<iostream>
using namespace std;
int main ()
{
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;
}
How is the compiler able to distinguish in the statement: "cin >> cin"?

If you run the program, you'll notice that it never waits for input.
It doesn't distinguish anything – you're right-shifting the int by its own value.
(And that value is indeterminate, so the program is undefined.)
If you increase the warning level of your compiler, you should see "Warning: statement has no effect" or something to that effect.

To add on to molbdnilo's answer:
When you are using the statement using namespace std;, you are telling the compiler that for all variables in the current scope, loop up the identifier in current scope, if not, look up in the parent scope, until the look up reaches global scope and still unable to find the identifier, then it will try to find it in the namespace you are using.
After you declared int cin, everything that is called cin in the main function will be the local int cin not the std::cin, so all of your codes are just left shifting cin and shifting "cin" by cin amount of bits.

Related

What will happen when we declare cin as int and take input from cin with print cin in cout?

#include <iostream>
using namespace std;
int main() {
int cin;
cin >> cin;
cout << "cin is : " << cin;
}
In this code it gets different output in different complier and can't find proper solution.
There are two things you probably don't understand: scope and initialization.
In the code below the global variable v is hidden by local variable v declared in main. All operations in main are performed on main's v. The same is true for cin. The cin you declared in main is not the same cin declared in std namespace. So, cin >> cin; has a different meaning. You probably expected the same behaviour as std::cin >> cin;.
double v;
int main()
{
int v;
}
c++ allows uninitialized variables. When you write int cin; memory space is allocated for cin, but nothing is written in (the variable is not automatically initialized). Leaving a variable uninitialized may be on purpose or not. Your compiler may be set to warn on uninitialized variables and/or check at run time. If you compile in debug configuration the variables may be automatically set to zero, depending on compiler, but you should not rely on this as your final build will be in release.
The answer to your question "Garbage value, Error, Segmentation fault, Nothing is printed" is garbage value (is this an interview question?):
cin is a local integer variable and
cin >> cin is different from std::cin >> cin and different from cin >>= cin.
Your code invokes undefined behavior. (Look up that term, it's an important concept that makes C++ an unreliable programming language.)
In the line int cin, you define a variable and don't initialize it.
The undefined behavior happens as soon as you read from the uninitialized cin variable.
The next undefined behavior happens depending on the value of cin. The shift-right operator is an arithmetic operation. If its right-hand side is not between 0 and the bit size of the left operand, the behavior is undefined.
you cannot declare keywords name for variable-name. cin and cout are keywords in c++.Please use different name for variable-name which used in your c++ program.

What will be the output of this C++ program?

#include<iostream>
using namespace std;
int main ()
{
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;
}
I saw this question here: http://quiz.geeksforgeeks.org/c-misc-c-question-8/
The output given by them is: cin + junk.
But I am unable to understand how it comes?
Please explain.
The "trick" in this question is
cin >> cin;
We're so used to seeing cin >> x to read x from the console that even when int cin; is present there is a chance you won't recognise cin >> cin as a bit-shift operation.
As has been mentioned, this is UB, which means you can't really expect anything. But in the absence of nasal demons, here's what you can sort of expect from a modern compiler:
The app chooses a register and calls it "cin".
It either does not overwrite whatever value that register still has from its last use, or - for a debug build - stores some magic number (chosen by the compiler author) into that register.
It then either shifts the value in cin right by cin bits and throws the answer away (i.e. cin is not modified by this operation.) - or the compiler eliminates cin >> cin completely because nothing after that line of code is dependant on the subtle side-effects it may have (such as setting the processor's zero flag)
The app then writes the string "cin" followed by the value in the register to the console.
The app ends cleanly, returning the value 0 to its caller (probably the OS).
tl;dr; It prints a random number because cin >> cin is a bit-shift operation with no side-effects, not an instruction to read input from the console.
The output given by them is: cin + junk.
While that is possible, the correct answer is: "I don't know, because the behaviour is undefined."
Let's go over the program line by line:
int cin;
A variable is default initialized. In this case, default initialization means that the value is indeterminate.
cin >> cin;
The bits of variable cin are shifted right for cin places. However, using an indeterminate value has undefined behaviour.
Rest of the program doesn't matter since behaviour is undefined.
In case you were wondering, std::cin is not involved because even though it is injected into the global namespace due to using namespace std, the local variable int cin shadows it.
Once cin is declared as integer, it can no longer be used for reading in operation.
Again it depends on scope of the cin variable. once the scope is over again cin functions as normal for reading in ops.
even same for cout also.

int cin. Still Working How? [duplicate]

This question already has answers here:
My cpp program is not being asking for input.
(2 answers)
Closed 5 years ago.
#include<iostream>
using namespace std;
int main ()
{
int cin;
cin >> cin;
cout << "cin" << cin;
return 0;
}
This is the program. I thought it should give an error. But it compiled and gave output as cin0. i.e. cin+junkvalue
P.S. I understand that cin >> cin, is a bit shift operation here.
But My Question is why are we able to declare int cin here?
You can declare any variable name at a different scope than some existing variable. cin is not a keyword or a reserved name, just an official name of the input stream. In fact, if you don't use using namespace std; in your code, you could do std::cin >> cin; and read an integer value from the standard input. [Should add that even with using namespace std;, you can still use namespace qualifiers, so std::cin >> cin; would work "with" as well as "without" that statement - I meant rather that it's a bad habit to use using namespace ... in general, I prefer to just type the namespace wherever it is needed]
Obviously, doing these sort of things are generally a bad idea. But it's well defined and "works" as long as you know what you are doing and don't need both at the same time.

Very basic C++ program issue - Invalid operands to binary expression

I just started teaching myself C++ on the Mac, and I have run into some issues.
I have written some code that allows the user to enter a number and when they hit enter, the number will be returned to the user.
Xcode will absolutely not have it though. Every time I try to run my code, it says that there is an issue with the cin>> thisisanumber; code.
The error comes up and says
Invalid operands to binary expression. Error is on line 10.
What am I doing wrong?
#include <iostream>
using namespace std;
int main()
{
int thisisanumber();
cout << "Please enter a number: ";
cin >> thisisanumber;
cin.ignore();
cout << "You entered"<< thisisanumber <<"\n";
cin.get();
}
You've fallen victim to the most vexing parse, which means thisisanumber is being treated as a function. Take out the parentheses and you should be fine:
int thisisanumber;
Also consider making it a bit more readable, such as thisIsANumber. If you ever need to know it, thisIsANumber uses the camel-case naming convention.
Declare your variable without brackets, like
int thisisanumber;
With brackets, it is interpreted as a function, and a function can't be passed as a parameter to the >> operator.
Your problem is the so called most vexing parse. Basically everything, which could be parsed as a function declaration will be parsed as such. Therefore the compiler will interpret int thisisanumber(); as a declaration of a function thisisanumber taking zero arguments and returning an int. If you consider this behaviour the problems with cin>>thisisanumber; should be somewhat selfevident.
If you remove the parantheses, changing the variable declaration to int thisisanumber;, your program should behave like you'd expect it to with thisisanumber being a variable of type int.
You might however reconsider your naming conventions, thisisanumber isn't exactly readable. I would suggest going with this_is_a_number, thisIsANumber or ThisIsANumber.
int thisIsANumber;
try making it variable declaration because what you wrote has been interpreted as function.
delete () after thisisanumber, because () after thisisanumber means that it's a function, when it's not.

How do I check the input data type of a variable in C++?

I have one doubt about how to check the data type of input variables in C++.
#include<iostream>
using namespace std;
int main()
{
double a,b;
cout<<"Enter two double values";
cin>>a>>b;
if() //if condition false then
cout<<"data entered is not of double type";
//I'm having trouble for identifying whether data
//is double or not how to check please help me
}
If the input cannot be converted to a double, then the failbit will set for cin. This can be tested by calling cin.fail().
cin>>a>>b;
if(cin.fail())
{
cout<<"data entered is not of double type";
}
Update: As others have pointed out, you can also use !cin instead of cin.fail(). The two are equivalent.
That code is hopelessly wrong.
iostream.h doesn’t exist. Use #include <iostream> instead. The same goes for other standard headers.
You need to import the namespace std in your code (…). This can be done by putting using namespace std; at the beginning of your main function.
main must have return type int, not void.
Concerning your problem, you can check whether reading a value was successful by the following code:
if (!(cin >> a))
cout << "failure." << endl;
…
Also, if my memory serves, the following shortcut should work:
if (! (cin>>a>>B)) { handle error }