i want to take an input from c++ function and return it to the main function
, i've already tried to do it but the function returns zero , any idea ?
#include<iostream>
using namespace std;
int input( int x);
int main()
{
int number;
input(number);
cout<<number;
}
int input (int x)
{
cin>>x;
return x;
}
you need to pass by reference
void input (int & x)
{
cin>>x;
}
or use the return value
int main()
{
int number;
number = input();
cout<<number;
}
int input ()
{
cin>>x;
return x;
}
You can change your function to make it take x by reference:
void input (int& x)
{
cin>>x;
}
This way, you don't even need to return x, because your function will update its value as it is passed by reference.
So, let's get it from the begining :
It any function, all its variables are temporary and only accessible in this function's scope unless you use a pointer or a reference(c++ only)
So what happen when you call your function is that a copy of number's is created into x
Also, the return statement of a function is used to... return values! Yeah, weird uh?
So actually you don't even need to send any parameter to your function and just take its result :
#include<iostream>
using namespace std;
int input();
int main()
{
int number = input(); // Takes what the return statement gives
cout<<number;
}
int input ()
{
int x;
cin>>x;
return x;
}
Here's another way by using c++'s references :
#include<iostream>
using namespace std;
void input( int& x);
int main()
{
int number;
input(number);
cout<<number;
}
int input (int& x)//Takes number's address
{
cin>>x;
}
Related
I am having issue in understanding that why my code is providing me some dummy value.
Can someone help me out that where I am at fault and what is the reason ?
#include <stdio.h>
#include <iostream>
class mypair
{
public:
int a,b;
public:
int print (int first , int second)
{
a = first;
b = second;
std::cout<<a <<" hello "<<b;
}
int getmax();
};
int mypair ::getmax()
{
int res;
res = (a>b)?a:b;
std::cout<<res;
return res;
}
int main ()
{
mypair abc;
std::cout<<abc.print(5,6);
std::cout<<abc.getmax();
}
print() doesn't return any value but it is expected to return an int. This is UB, and your dummy values are caused by this.
In addition, in both print() and getmax() you send output to cout. In the case of getmax(), this output will immediately predede the output of the return value, causing the same number to be displayed twice without any space or separator.
Please assume the version of gcc 7.2.1 in this question
I would like to declare a global variable which behave like a const however, the value to initialize it cannot not be detected before the program being executed. In other words, the target variable would be re-assigned since the first time it is assigned.
An ugly approach of this concept as follow:
#include<iostream>
int numberOfPeople; //Do not re-assign it after it first assign
int main(){
std::cin >> numberOfPeople; // Do not re-assign numberOfPeople since then !!!
// Following of codes omitted.
}
As you could see, this is a very ugly approach and cannot be checked by compiler. I wonder whether there is a kind of notation in c++ that can freeze the variable since it first assigned.
So I can write code like this:
#include<iostream>
magic_notation int numberOfPeople;
int main(){
std::cin >> numberOfPeople; // Allowed as it's first assign.
// Median codes omitted.
numberOfPeople = 60. //Disallowed and will get an error message from compiler!
// Following codes omitted.
}
Is there any kind of notation as can use like the magic_notation in the code above in c++?
The best approach is to make a class with a public const member variable which gets initialized in the constructor:
struct InitInfo {
const int numberOfPeople;
InitInfo() numberOfPeople(getNumberOfPeople()) {
}
private:
static int getNumberOfPeople() {
int res;
cin >> res;
return res;
}
};
InitInfo initInfo;
Now you can use the member variable as follows:
int main() {
cout << initInfo.numberOfPeople << endl;
}
You can use the same approach for initializing a global variable, too.
static int getNumberOfPeople() {
int res;
cin >> res;
return res;
}
const int numberOfPeople = getNumberOfPeople();
int main() {
cout << numberOfPeople << endl;
numberOfPeople += 10; // <<== This triggers an error
}
One approach you can use is to wrap the variable as a static variable in a function. Use the function instead of the variable in rest of your code.
#include <iostream>
int readFromStdin()
{
int n;
cin >> n;
return n;
}
// Wrap it arund in a function.
// int numberOfPeople; //Do not re-assign it after it first assign
int getNumberOfPeople()
{
// Initialize by reading from stdin.
static int numberOfPeople = readFromStdin();
returnn numberOfPeople;
}
int main(){
// Use the function instead of the variable.
getNumberOfPeople();
}
In case you have different ways to initialize the variable, you could come up with something like this:
struct {
int value() const { return _val; }
void init(int val) {
if(!_set) _val = val;
}
private:
int _val;
bool _set = false;
} numberOfPeople;
Now, everybody who uses the variable should call init before using it to make sure it is initialized.
I have written this program but it doesn't work. It gives an error that x and y was not declared and expected primary expression before int on line 17.
#include<iostream>
using namespace std;
class shapes
{
int width, height;
public:
int getvalue();
void decideshape(int l, int b);
};
main()
{
cout<<"to find what type of shape you have input the measurements"<<endl;
shapes toy;
toy.getvalue();
toy.decideshape();
}
int shapes::getvalue()
{
int l, b;
cout<<"length = ";
cin>>l;
cout<<"breath = ";
cin>>b;
}
void shapes::decideshape(x, y)
{
if(x==y)
cout<<"This is square"<<endl;
else
cout<<"This is rectangle"<<endl;
}
how should i return 2 values from function getvalue
Arguments are required to have types in C++. Write your definition of shapes::decideshape as
void shapes::decideshape(int x, int y)
You don't return a value from shapes::getvalue.
You pass too few (actually none) parameters to shapes::decideshape. Two ints are expected to be supplied.
You need to tell the compiler what a function returns explicitly. Add the int return value to main.
You are missing the type of x and y in the parameter list:
void shapes::decideshape(int x, int y)
I am curious about how to call function pointer in a map structure. Here is the details:
#include<iostream>
#include<map>
#include<vector>
#include<string.h>
using namespace std;
class FuncP;
typedef int(FuncP::*func) (int, int);
class FuncP
{
public:
map<int, func> fmap;
map<int, string> fstring;
public:
FuncP(){}
void initial();
int max(int x, int y);
int min(int x, int y);
int call(int op, int x, int y)
{
return (this->*fmap[op])(x, y);
}
};
void FuncP::initial()
{
fmap[0] = &FuncP::max;
fmap[1] = &FuncP::min;
fstring[0] = "fdsfaf";
}
int FuncP::min(int x, int y)
{
return (x<y)?x:y;
}
int FuncP::max(int x, int y)
{
return (x<y)?y:x;
}
int main()
{
func h = &FuncP::max;
FuncP *handle = new FuncP();
handle->initial();
cout<< handle->call(0, 1, 4); //1
cout<< (handle->FuncP::*fmap)[0](1,5); //2
return 0;
}
For the number 2 (handle->FuncP::*fmap)0; The compiler gives a error:
‘fmap’ was not declared in this scope
I am not sure why it happened. What the difference of the number 1 and 2 call methods?
As commented by Piotr, a correct way would be
(handle->*(handle->fmap[0]))(1, 5);
Explanation:
handle->fmap[0] gives you the function pointer. To call it, you need to dereference it, giving *(handle->fmap[0]) (parentheses optional)
and call it on the respecting object (handle), leaving us with the expression above.
This is essentially the same as your above statement (this->*fmap[op])(x, y) except of handle->fmap[0]instead offmap[op].
I am new to c++ and have a couple questions regarding passing arrays by reference to functions (so that the arrays are modified by the function). I realize there are similar questions that have been asked already, but there are a few points that I think were not covered in those previous questions (at least from what I saw). From what I have gathered so far, one can pass an array by reference by doing the following:
#include<iostream>
using namespace std;
void modify_array(int* a);
int main()
{
int array[10];
modify_array(&array[0]);
for(int i=0;i<10;i++)
{
cout<<array[i]<<endl;
}
}
void modify_array(int* a)
{
int i;
for(i=0;i<10;i++)
{
*(a+i)=i;
}
}
This makes sense to me but if I change the function to:
void modify_array(int* a)
{
int i;
for(i=0;i<10;i++)
{
a[i]=i; //line changed
}
}
This also works. Is there a difference? Or is the second just a short cut? Also in the case of passing 2d arrays I would have guessed that the following code would work:
#include<iostream>
using namespace std;
void modify_array(int* a);
int main()
{
int array[10][10];
modify_array(&array[0][0]);
}
void modify_array(int* a)
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
a[i][j]=i*j;
}
}
}
But this doesn't. From what I have seen in other related questions, you would do something like:
void modify_array(int (*a)[10])
{
int i,j;
//a[i][j]= blah blah blah;
}
or,
void modify_array(int (&a)[10][10])
{
int i,j;
//a[i][j]= blah blah blah;
}
What is the difference between these latter two function definitions? What do experienced c++ programmers recommend using: the (*a)[10][10] notation or the (&a)[10][10] notation?
Writing *(a+i)=i; or a[i]=i; are equivalent. The first is seen as an offset applied to the pointer to the array and assigning the value to the pointee, while the second is assigning the value to the element of the array.
However, when passing a pointer to a function modify_array(int* a), it cannot deduce that the pointee is a 2D array, and does not know what size to offset to address the other lines of the array, with a[i][j]=i*j;. For the compiler, it can only access the first dimension of the array.
The proper way to do what you need is this
#include<iostream>
using namespace std;
void modify_array(int (&a)[10][10]);
int main()
{
int array[10][10];
modify_array(array);
for(int i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
cout<<array[i][j]<<endl;
}
}
}
void modify_array(int (&a)[10][10])
{
int i;
for(i=0;i<10;i++)
{
for(int j=0;j<10;j++)
{
a[i][j]=i*j;
}
}
}
Live example
The function is expecting an int array of 10x10, passed by reference.