Initializing Variable Through Function - c++

I'm learning pointers and references but I'm having trouble grasping the concept. I need to declare a variable in my main function and then have it initialized through a function by user input, without returning anything. I've tried:
#include <iostream>
using namespace std;
void input(int &num){
cout << "Enter A Number" << endl;
cin >> static_cast<int>(num);
}
int main(){
int x;
input(x);
cout << "The Number You Entered Was " << x << "!" << endl;
return 0;
}

You are doing it correctly, except for that static_cast<int> there. What is it doing there? What made you use that cast?
Get rid of that cast, and it should work. This
cin >> num;
is all you need.
P.S. Just keep in mind that in C++ terminology the term initialize has very specific meaning. Formally, initialization is always a part of variable definition. Whatever changes you do to that variable after the definition is no longer initialization. In your case variable x is declared without an initializer, which means that it begins its life uninitialized (with indeterminate value). Later you put some specific value into x by reading it from cin, but this is no longer initialization (in C++ meaning of the term).
It might be a good idea to declare your x with some determinate initial value, like
int x = 0;
although personally I'm not a big fan of "dummy" initializers.

You should drop the static_cast.
cin >> num;
std::cin's operator>> has overloads that take integral types.
Note that you are not initializing a variable through a function at all. You are assigning a value to a variable by passing a reference to it to a function.

No need for the static_cast stuff. Your function is given a reference to an int, and you want to read an int. Since you've passed a reference to the variable, the changes to it in your input function will be reflected in the caller.

Related

Why doesn't cin have ampersand operator or specifier format like scanf() does in C?

Like I encountered this doubt while learning dynamic memory allocation in C++, and just can't focus anymore on learning it now. :(
int n;
cout << "Enter array size: ";
cin >> n;
int *p = new int[n];
So everything is fine till now, I just allocated n blocks of int memory in heap area
Now, while taking the input using a for loop, I had this doubt while I tried to write p[i] as *(p+i)
for (int i = 0; i < n; i++)
{
// cin >> p[i]; // This is correct
// cin >> *(p+i); // This is correct
cin >> (p + i); // same as cin >> &p[i], right? Now, this gives me error since I didn't deference
// it and now I'm confused as to why we need to deference it? *(p+i) tells which
// block the value is to be stored in, but doesn't (p+i) also give us the same
// address? The input value should still have been stored in the respective memory
// block, right? But it doesn't and I can't visualize it why?
// Also, now I'm even confused as to why writing cin >> n works and writing cin >> &n doesn't??
}
I was simply expecting that my value should still be accepted into the respective array element, but it didn't, rather it gave me a very very wrong error, which I'm unable to understand.
I tried looking for answers, but still unclear with the concept visualization and clarity. All I've known so far is that cin is an object of istream class, >> operator while used with cin is kind of like a function call, and the variable name which we write after the >> operator is "passed by reference" or something like that, which might seem like that is why maybe we don't give address as reference variable already has it by default, but I'm not sure and still in doubt.
Please someone explain it in proper sequence and with proper example. I'll be grateful.
Type of *(p + i) is int and type of (p + i) is int*. With the first one you are reading an integer, so that is clear.
Why doesn't cin >> (p + i) read int? When a function takes parameter by reference, the parameter must be the same exact type. You are giving it int*, so it will try to read int*.
How would we read a pointer? I guess we could read an integer and assign it to the pointer variable. We are currently reading to the temporary value p + i. operator>> needs a reference, which it cannot get for a temporary value, which is why you get a compile error.
Let us skip this problem by using another variable:
int* pi = p + i;
cin >> pi;
This still does not compile, because there is an overload for reading void*, but not int*. In C++, you cannot automatically convert between two pointer types. If you want to read int*, you can do that, but you have to write an overload for operator>>.
the variable name which we write after the >> operator is "passed by reference"
This is exactly the point. One of the main goals of the C language was to build a rather simple compiler able to provide efficient code. As a result, it tried to remain as explicit as possible and only allowed to pass parameters to functions as values. If you want to modify something from a function you just pass a pointer to it.
C++ language is aimed at a much higher level. Proper pointer handling is not always trivial and memory allocation is not either. The philosophia of C++ is that those are gory details that should be hidden to a high level program. For that reason, many SO users advise to never use new[] and delete[] (explicit allocation) but rely on containers which correctly handle the subtilities of automatic deallocation, and copy and move semantics.
For the same reason, references were introduced in the language. At first sight, they just look like disguised pointers to old C programmers, meaning useless syntactic suger, and worse contradictory with the C idiom requiring a pointer to modify a variable from a function (what operator << indeed is at a lower level). But that is exactly what they are for: you can act directly on the variable without explicitly dereferencing it, which removes the risk of forgetting a * somewhere in the code.
And actually, the signature of the stream extractor is:
istream& operator << (istream& in, int& val);
So the function is able to modify the stream itself and the passed variable.

Local Variables Being Passed ( C++)

I have encountered a problem in my learning of C++, where a local variable in a function is being passed to the local variable with the same name in another function, both of these functions run in main().
When this is run,
#include <iostream>
using namespace std;
void next();
void again();
int main()
{
int a = 2;
cout << a << endl;
next();
again();
return 0;
}
void next()
{
int a = 5;
cout << a << endl;
}
void again()
{
int a;
cout << a << endl;
}
it outputs:
2
5
5
I expected that again() would say null or 0 since 'a' is declared again there, and yet it seems to use the value that 'a' was assigned in next().
Why does next() pass the value of local variable 'a' to again() if 'a' is declared another time in again()?
http://en.cppreference.com/w/cpp/language/ub
You're correct, an uninitialized variable is a no-no. However, you are allowed to declare a variable and not initialize it until later. Memory is set aside to hold the integer, but what value happens to be in that memory until you do so can be anything at all. Some compilers will auto-initialize variables to junk values (to help you catch bugs), some will auto-initialize to default values, and some do nothing at all. C++ itself promises nothing, hence it's undefined behavior. In your case, with your simple program, it's easy enough to imagine how the compiler created assembly code that reused that exact same piece of memory without altering it. However, that's blind luck, and even in your simple program isn't guaranteed to happen. These types of bugs can actually be fairly insidious, so make it a rule: Be vigilant about uninitialized variables.
An uninitialized non-static local variable of *built-in type (phew! that was a mouthful) has an indeterminate value. Except for the char types, using that value yields formally Undefined Behavior, a.k.a. UB. Anything can happen, including the behavior that you see.
Apparently with your compiler and options, the stack area that was used for a in the call of next, was not used for something else until the call of again, where it was reused for the a in again, now with the same value as before.
But you cannot rely on that. With UB anything, or nothing, can happen.
* Or more generally of POD type, Plain Old Data. The standard's specification of this is somewhat complicated. In C++11 it starts with §8.5/11, “If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value.”. Where “automatic … storage duration” includes the case of local non-static variable. And where the “no initialization” can occur in two ways via §8.5/6 that defines default initialization, namely either via a do-nothing default constructor, or via the object not being of class or array type.
This is completely coincidental and undefined behavior.
What's happened is that you have two functions called immediately after one another. Both will have more or less identical function prologs and both reserve a variable of exactly the same size on the stack.
Since there are no other variables in play and the stack is not modified between the calls, you just happen to end up with the local variable in the second function "landing" in the same place as the previous function's local variable.
Clearly, this is not good to rely upon. In fact, it's a perfect example of why you should always initialize variables!

Why doesn't cin have specifier format or ampersand like scanf?

Having
int a;
in C++, why doesn't
cin >> a;
need ampersand like
scanf("%d", &a);
in C ?
In C++, we have not only variables and pointers (as in C), but also references. On the calling side, passing a reference looks like passing a variable by value, but on the side of the function called, it actually receives not a copy, but a reference to the actual variable and hence can alter it. You can think of a reference like a pointer but without the need to de-reference.
std::istream& operator>> (std::istream&i, some_type&x);
declares an operator that takes a reference to a std::istream and another to some_type and returns the std::istream reference. With this declaration you can now
some_type x;
std::cin >> x; // calls above operator, pasing x by reference
Passing by reference and passing by pointer are very similar, and may actually produce identical code:
void f1(int*x) { *x=2; }
void f2(int&x) { x=2; }
int a;
f1(&a); // is equivalent
f2(a); // to this
The common wisdom in C++ is to pass variables that shall not be altered either by value (if they fit into a single register) or by const reference. Variables that may be altered by the function called can either be passed by (non-const) reference or by pointer, this is a matter of style: with the latter it is explicit at function call that the variable can be altered, while the former (passing by reference) requires one to look up the API of the function to find out whether one passes by value, reference, or const reference.
cin and i are passed by reference to operator >> given it the ability to read and write cin and i.
As C has no true reference passing, scanf("%d", &a); code needs to pass the address of a for scanf() to write a value to a.
C and C++ use fundamentally different methods when passing arguments of varying type.
In C, a single function like scanf(const char* pattern, ...) can accept many different types of parameters. That's why it needs a pattern parameter where you tell it the actual types it has received. If you pass anything unexpected, you have a runtime issue.
In C++, a single function name may be implemented repeatedly for different types of parameters. This is called overloading. Each overloaded implementation will know exactly what it expects, and the compiler will assure that it only gets that type of values. If there's no matching overload, you have a compile-time error.
Another difference is that in C++, cin >> i is actually a function call of operator>>. In C, function calls all look like functionName(argument)
You can use scanf in c++ , How ever still better to use cin. "cin>>"not "cin<<"
#include <iostream>
#include <stdio.h>
using namespace std;
int main(){
float x;
scanf("%f",&x);
printf("%.1f",x);
return 0;
}

C++ basic integer confusion [duplicate]

This question already has answers here:
How does the Comma Operator work
(9 answers)
Closed 9 years ago.
I simply have the line as follows:
int player = 1, i, choice;
My question is, what is assigned to i and what is assigned to choice? I was always taught that a variable could not be assigned to multiple values.
That code is equivalent to saying
int player = 1;
int i;
int choice;
You are not assigning 1, i, and choice into the integer variable player.
Nothing is assigned anywhere in this -- it's doing initialization not assignment.
player is obviously initialized to 1.
If this definition is at namespace scope so i and choice have static storage duration, then they will be zero-initialized.
If this definition is local to a function, i and choice will be default-initialized, which (in the case of int) means they aren't given a predictable value.
If this definition is inside a class, then i and choice can be initialized by a constructor. A constructor generated by the compiler will default-initialize them.
They (i and choice) have unspecified values. They can be pretty much any value, really. Unless you explicitly set them to a value, they are given some "junk" value (typically whatever is already in that memory location that they've been assigned).
You're not assigning to player multiple times. You're creating 3 variables, and assigned 1 to player. It's the same as if you had written:
int player = 1;
int i;
int choice;
Think of this as:
int player = 1;
int i;
int choice;
In c++ you are allowed to declare multiple of the same data type on the same line, like
char c1, c2, c3;
and it is also accepted to give one of these a value in their declaration, like what your line is doing. So as simonc said, there will be no value in i or choice.
What you have there is definition & initialization, definition, definition;
int player = 1;
int i;// = most probably 'random' trash from heap/stack memory
int choice;// = most probably 'random' trash from heap/stack memory
i and choice aren't defined. What happens is, you are saying:
I want to declare player as int and asign 1 to it then a sequens interupt sign(,), says the type specifier has reference to the next sequenz. Means also to declare i and choice as int (but without asigning anythign)

const values run-time evaluation

The output of the following code:
const int i= 1;
(int&)i= 2; // or: const_cast< int&>(i)= 2;
cout << i << endl;
is 1 (at least under VS2012)
My question:
Is this behavior defined?
Would the compiler always use the defined value for constants?
Is it possible to construct an example where the compiler would use the value of the latest assignment?
It is totally undefined. You just cannot change the value of constants.
It so happens that the compiler transforms your code into something like
cout << 1 << endl;
but the program could just as well crash, or do something else.
If you set the warnings level high enough, the compiler will surely tell you that it is not going to work.
Is this behavior defined?
The behavior of this code is not defined by the C++ standard, because it attempts to modify a const object.
Would the compiler always use the defined value for constants?
What value the compiler uses in cases like this depends on the implementation. The C++ standard does not impose a requirement.
Is it possible to construct an example where the compiler would use the value of the latest assignment?
There might be cases where the compiler does modify the value and use it, but they would not be reliable.
As said by others, the behaviour is undefined.
For the sake of completeness, here is the quote from the Standard:
(§7.1.6.1/4) Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior. [ Example:
[...]
const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object
]
Note that the word object is this paragraph refers to all kinds of objects, including simple integers, as shown in the example – not only class objects.
Although the example refers to a pointer to an object with dynamic storage, the text of the paragraph makes it clear that this applies to references to objects with automatic storage as well.
The answer is that the behavior is undefined.
I managed to set up this conclusive example:
#include <iostream>
using namespace std;
int main(){
const int i = 1;
int *p=const_cast<int *>(&i);
*p = 2;
cout << i << endl;
cout << *p << endl;
cout << &i << endl;
cout << p << endl;
return 0;
}
which, under gcc 4.7.2 gives:
1
2
0x7fffa9b7ddf4
0x7fffa9b7ddf4
So, it is like you have the same memory address as it is holding two different values.
The most probable explanation is that the compiler simply replaces constant values with their literal values.
You are doing a const_cast using the C-like cast operator.
Using const_cast is not guaranteeing any behaviour.
if ever you do it, it might work or it might not work.
(It's not good practice to use C-like operators in C++ you know)
Yes you can, but only if you initiate a const as a read-only but not compile-time const, as follows:
int y=1;
const int i= y;
(int&)i= 2;
cout << i << endl; // prints 2
C++ const keyword can be missleading, it's either a const or a read-only.