I'm very new to C++ and was wondering if there was a way to return integer input from a function directly without storing it in a variable.
To be more clear:
#include <iostream>
int function()
{
std::cin >> (return function here???)
}
int main()
{
int number = function()
std::cout << number
return 0;
}
Thanks for any help.
if there was a way to return integer input from a function directly without storing it in a variable.
There is not. All standard input interfaces take an object argument which they modify rather than return the resulting value1.
A possible reason for this design is that it is very typical for input to be bad. Only way to avoid returning an int from a function declared to return int is to throw (or terminate the process, but that would be silly). And input error is perhaps considered so non-exceptional that using exceptions for control flow of input handling may be considered inappropriate. This is just my reasoning, not an authoritative explanation for the design choice.
If you fix your function to be correct, with the variable that is necessary and checking for errors, then you can use that function to do exactly that:
return function();
1 With the exception of std::istream::get() and the corresponding C style std::getc and std::fgetc which you can use to extract a single character that they return directly.
Related
I know that for reading from console we can use
int number;
cin >> number;
//A line of code where we use int number
But is it possible to read a number from console without any variables. Are there any methods that return a number from console?
But is it possible to read a number from console without any variables.
Read a number without using any variable – sounds like a puzzle.
Here we go:
#include <iostream>
int main()
{
return !std::cin.operator>>(*new int());
}
This program returns
0 … on success (input was a number)
1 … on error (input was not a number).
Output:
Test 123:
Error: 0
Test abc:
Error: 1
Live Demo on coliru
Note:
I somehow had to provide a temporary LValue to the stream input operator.
I had no better idea than *new int() though I know this makes a memory leak.
In this simple program, this won't hurt as the OS will make the clean-up for me.
Are there any methods that return a number from console?
This part was really unclear to me.
If I had this problem on my own I would make a helper function
int readNum(std::istream &in)
{
int number; in >> number; return number;
}
which I could use then in the main() function without any variable
int main()
{
std::cout << "Number: " << readNum(std::cin) << '\n';
}
but readNum() had again to use a variable to store the result of formatted input.
It's hard to use formatted input stream operators without any variable if the result of input should be accessed again (at least, in C++ with std library only).
The getchar() function allows you to ignore one character instead of using a variable to save the value.
This question already has answers here:
Which is more efficient: Return a value vs. Pass by reference?
(7 answers)
Closed 2 years ago.
I have been learning C++ and came across a function, but the return type was a vector.
Here is the code:
vector<Name> inputNames() {
ifstream fin("names.txt");
string word;
vector<Name> namelist;
while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
namelist.push_back(name);
}
return namelist;
}
name is part of a struct defined as:
struct Name {
string first_name;
string last_name;
bool operator<(const Name& d) const {
return last_name > d.last_name;
}
void display() {
cout << first_name << " " << last_name << endl;
}
};
What is the purpose of using vector< Name>inputName()? What is it doing?
And why can I just not create a void function and pass a vector through it?
I.e.:
void input(vector<Name>&v){
ifstream fin("names.txt");
string word;
while (!fin.eof()) {
Name name;
fin >> name.first_name;
fin >> name.last_name;
v.push_back(name);
}
}
Your question is basically: Do I return by value or do I use an output argument?
The general consensus in the community is to return by value, especially from C++17 on with guaranteed copy elision. Although, I also recommend it C++11 onwards. If you use an older version, please upgrade.
We consider the first snippet more readable and understandable and even more performant.
From a callers perspective:
std::vector<Name> names = inputNames();
It's clear that inputNames returns you some values without changing the existing state of the program, assuming you don't use global variables (which you actually do with cin).
The second code would be called the following way:
std::vector<Name> names;
// Other code
inputNames(names);
This raises a lot of questions:
does inputNames use the names as input or does it extend it?
if there are values in names, what does the function do with it?
does the function have a return value to indicate success?
It used to be good practice when computers were slow and compilers had troubles optimizing, though, at this point, don't use it for output arguments.
When do you use the last style: if you want an in-out argument. In this case, if you intend to append, the vector already had data, and that actually makes sense.
This basically mirrors the mathematical definition of a function as...
...a relation that associates an input to a single output.
While you could write void functions that modify their parameters, this has disadvantages:
Expression of intent. Consider a function taking multiple parameters. Which ones are input, which ones are output?
Clarity of purpose. A function modifying multiple values at once is usually (not always) attempting to do too many things at once. Focussing on one return value per function helps with keeping your program logic under control.
RAII. You can't use a void function to initialize a variable, meaning you would have to declare that variable first (initialized to some "default" value), then initialize it to the desired value.
There are languages that work without return values, using "out parameters" instead. You can do it this way in C++ as well. But all in all, using return values as the one output of a function helps the structure of your program.
vector<Name> is the return value of the method. It will create a new object with a vector of the structs.
Your implementation is called "call by reference". It will pass the pointer to an existing vector. As a example, with the call by the reference implementation, you could call input(vector<Name>&v) multiple times and your preexisting vector will have multiple times the content. If you would to it with the vector return value, it would always create a new object with only one iteration of data.
I need to check if a variable is initialised. I am new to C++ so perhaps I am thinking about this in the wrong way. I want to do the following:
if (variable) {
// do some stuff
}
My first thought was to set the value to NULL at declaration. However, it turns out NULL is identical to 0 in C++. Unfortunately my variable is a double that can be 0. The solutions I could find online are all regarding pointers and just say to use nullptr but this is not possible in my case of course.
What alternatives do I have here?
General way to do this is to use std::optional
https://en.cppreference.com/w/cpp/utility/optional
This data type wraps the inner type and provides methods to tell you if it has been set or not.
Note that you'll need a C++ 17 compiler.
Here's an example. You can see it's pretty easy to use and you don't need to create sentinel values (i.e. special values that are interpreted for the case of being not set).
#include <iostream>
#include <cstdlib>
#include <optional>
using namespace std;
int main()
{
optional<double> speed;
if (!speed)
{
cout << "speed not set" << endl;
}
speed = 0;
if (speed)
{
cout << "speed set to " << *speed << endl;
}
}
My knowledge in C++ is very limited, but judging from your description I believe that you are using primitive built-in type of C++ (int, double, bool, ...). If this is the case, then it is hard to know if your variable has been initialized since the primitive type all have their default value in case it is declared but not assigned a value.
One way I used to walk around this problem is that always init the variables with special default values. However, if the variables happen to be assigned values that match the default, that could be a problem.
However, I find it rarely happen because if you are using a library, then the class should have a method/ variable... to let you know the status of the current instance if necessary. Otherwise, the class should init default valid values, or you are using it the wrong way. If you are creating your own class, then it is easy to add a status variable to it, right?
Like I said, my knowledge is very limited, I could be wrong though.
I would like to know the difference between functions that return a value and functions that set a value to a pointer, for example:
Pointer:
int myVal;
ptr_multiply(5, 5, &myVal);
cout << myVal << endl; //Output: 25
Return:
int myVal = rtn_multiply(5, 5);
cout << myVal << endl; //Output: 25
My question focuses in what method to choose when creating functions and why, as well as what advantages/disadvantages can we find in each of them.
Readability is the main reason functions typically return what you expect them to return. However, as this is highly subjective, I suggest you strive for consistency within your project.
When you want a function to return multiple things and not group them all together in a structure just so you can return them, an alternative is to return them in output parameters.
If you have big pieces of data to return, then you might come across to performance-bottlenceks. The reason is that that the returning value must be copied.
But in the most cases you don't have to worry about that, because modern compilers are capable of auto-inline things like that.
Side note: In C++ try to avoid naked pointers as much as possible (use references, smart-pointers)
One advantage to use the "pointer" method is that you can have multiple "return" values by passing in non-const references or pointers. For example:
int output1;
int output2;
get_values("input", &output1, &output2)
You can return a success/failure:
int v = -1;
if(ToInt("wibble",&v)){
// do something with v
}
Would fail as "wibble" can't be converted to an int.
The other useful thing is that the function doesn't have to change v:
int v = previousValue;
UpdateIfNewValueFound( &v )
Return the value. With modern compilers there should be almost no difference in performance between the two, but returning the value has several advantages:
By definition, it's what a function should do (i.e. a function maps from a domain to a codomain).
It's self-documenting; if I'm using an unfamiliar API, unless there is good documentation, it can get confusing what is input/output if values are returned in the parameter set. With a returned value there is no ambiguity, and requires less documenting.
It's easier to use - can half the number of lines needed! Compare
int r = f();
to
int r;
f(&r);
It could make you a better programmer; you have to put more effort into returning multiple values from a function (e.g. via a struct or pair, as opposed to adding another parameter). If you find you need to do this often, the additional effort may force you to think more carefully about your code design - it's usually better for a function to just do/return one thing.
Another difference is stack or heap.
A return-value lies on top of the stack. The pointer-variant lies in heap.
For instance (sensless recursive code to demonstrate return on stack):
typedef std::array<int,1000> KByte;
KByte tmp;
KByte f(int nr) {
if (nr == 1) { tmp[nr]=nr; return tmp; }
else { tmp[nr]=nr; return f(nr-1); };
}
void f2(int nr, KByte& ret) {
if (nr == 1) { ret[1]=1; }
else { ret[nr]=nr; f2( nr-1, ret ); }
};
Calling
KByte t = f(999); /* Stack error */
shoud give you an stack-size error, since 1000 KByte (1GB) on the stack is to much.
Calling
KByte t2;
f2( 999, t2 );
should work without stack problem. (It also uses recursion depth 1000, but does not lie the return value on the stack.
I am working on a piece of structured programming homework that requires that I make a program that allows the user to enter names blah blah blah and so on. What I want to do after putting names into the string array is to print them to the screen. I had hoped to accomplish this by passing the array and the number of names contained therein to a function that would then print them to the screen. I wanted to pass the array and number of names as constants so that it would safeguard them so they couldn't be modified by the function, just read-only. I don't understand why I can't put const before the string array or the number of names though.
void writeNames (const string namelist[], const int number_of_names)
Is this something I just have to accept or is there a way I can pass both of those as read-only to the function? I can complete the homework without this so this is more a question of curiousity than a "help me with my homework" one.
P.S. Vectors seem to be a way of doing a lot more things with strings and such, but we haven't got to them in class yet and therefore I can't use them yet either.
Thanks
Without seeing what you're doing within the function, it's hard to answer the question, but my crystal ball says that you're probably doing something that could potentially modify one of the parameters within your method, so the compiler is complaining because you declared the parameter const.
As an example, something like this works just fine:
void writeNames(const std::string namelist[], const int number_of_names)
{
for(int i = 0; i < number_of_names; i++) {
std::cout << namelist[i] << std::endl;
}
}
However, something like this would cause a compiler error, since you're changing one of the variables:
void writeNames(const std::string namelist[], const int number_of_names)
{
while(number_of_names--) { // <-- We're modifying a const value here
std::cout << namelist[count] << std::endl;
}
}
Incidentally, putting the const modifier on your "number_of_names" parameter is somewhat redundant since you're passing the parameter by value, so changing the value within the function would have no effect on the value of the input parameter in the calling function. A change in any of the strings in the array, however, would be reflected in the calling function, so the const modifier there makes sense. Generally you would use const only on parameters that are either pointers, or being passed in by reference.