I'm new in C++ programming world and I have not understood yet if it's possible (and how) to use an output from a function as input to another function.
#include <iostream>
using namespace std;
int func(int l, int m) {
int x = l * m;
return x;
}
int code(x?) {
...
}
I would like to use output from func (the value x) as an input for code.
Is it possible? How could I do that?
Thanks for the help
EDIT 1:
Really thanks for the answers. Is it possible also to pass values between functions using pointers?
Functions only "have" values while they are executed.
You can either call the first from the second funtion,
or call the first function, read the return value into a variable and give that value as parameter to the second,
or call the second and give one of its parameters directly as return value from a call to first function.
Here are some examples of the three options, using 1,2,3 as arbitrary integers.
Variant 1:
int func(int l, int m) {
int x = l * m;
return x;
}
int code(void) {
int ValueFromOtherFuntion=func(1,2);
return 3;
}
Variant 2:
int func(int l, int m)
{
int x = l * m;
return x;
}
int code(int XfromOtherFunction)
{
return 3;
}
int parentfunction(void)
{
int ValueFromOtherFuntion=func(1,2);
return code(ValueFromOtherFunction);
}
Variant 3:
int func(int l, int m)
{
int x = l * m;
return x;
}
int code(int XfromOtherFunction)
{
return 3;
}
int parentfunction(void)
{
return code(func(1,2));
}
Yes, what you are looking for is called function composition.
int sum(int a, int b)
{
return a + b;
}
int square(int x)
{
return x*x;
}
int main()
{
std::cout << square(sum(5, 4)); //will calculate (5+4)squared
}
When you write the functions, assume that you already have all the input and proceed just writing what you want that function to do.
As to when you use that function, use "nested functions" or a function inside a function as such:
code(func(l, m));
Function func will execute first and return the value x, thus leaving you with code(x) which will execute after. Its like pealing an onion: one layer to the other.
#include <iostream>
int func(int l, int m) {
int x = l * m;
return x;
}
void code(int x) { // argument type is the same as the return type of func
std::cout << x;
}
int main (){
int result = func(1 ,2); // either store it
code(func(1, 2)); // or pass it directly.
std::cout << result;
return -1;
}
You can call it in your main function (or in any other within scope for what matters):
code(func(l,m))
I would like to know how to define a variable in one function and access and change it in another function.
For example:
#include <iostream>
void GetX()
{
double x = 400;
}
void FindY()
{
double y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
int main()
{
GetX();
FindY();
PrintXY();
}
How would I access these variables from all the functions? (Obviously for this to work in real life I wouldn't need so many functions, but I think this is a nice simple example). Thanks in advance for your help!
Use function parameters to pass values to functions and return values to return results:
#include <iostream>
double GetX()
{
return 400;
}
double FindY(double x)
{
return x + 12;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double x = GetX();
double y = FindY(x);
PrintXY(x, y);
}
Since the question was tagged with C++, here is another option:
#include <iostream>
class Sample
{
public:
void FindY()
{
y = x + 12;
}
void PrintXY()
{
std::cout << x;
std::cout << y;
}
private:
double x = 400, y;
};
int main()
{
Sample s;
s.FindY();
s.PrintXY();
}
You want to define a variable in one function : That means you are making the variable local to that function.
You want to access and change that local variable from another function. This is not usual. Technically possible but can be done with better resource management/design.
*You can make the variable your class member and play with it.
*You can share a variable by making it global as well.
*In Tricky way :
double &GetX()
{
static double x = 400;
return x;
}
// We are accessing x here to modify y
// Then we are modifying x itself
// Pass x by reference
double &AccessAndChangeX(double& x)
{
static double y;
y = x + 12; // We are accessing x here and using to modify y.
// Let's modify x
x = 100;
return y;
}
void PrintXY(double x, double y)
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX(); // Take the initial value of x. 400.
double &y = AccessAndChangeX(x);
//Print initial value of x and value of y(generated using x)
PrintXY(x, y);
// X was modified while AccessAndChangeX(x). Check if x was changed!
std::cout << "\n" << "What is the value of x now : " << GetX();
}
1st, make x, y as static, so that these exist when the function returns..
2nd, get reference, modify or do something outside the function..
#include <iostream>
double &GetX()
{
static double x = 400;
return x;
}
double &FindY( double x )
{
static double y;
y = x + 12;
return y;
}
void PrintXY(double x, double y )
{
std::cout << x;
std::cout << y;
}
int main()
{
double &x = GetX();
double &y = FindY( x );
// Now you can modify x, y, from Now On..
// .....
PrintXY( x, y );
}
By the way, I donot recommend this style of code..
I have a function which takes in two int values, does some processing and then returns the processed values in the form of a struct to the calling function.
The following is my called function:
auto start_end(){
bool cond = false;
int xd = 0;
int yd = 0;
std::cout<<("Please enter a desired x coordinate")<<std::endl;
std::cin>>xd;
while(std::cin.fail()){
std::cout<<("That is not a valid integer. Please enter a valid x co-ordinate")<<std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin>>xd;
}
std::cout<<("Please enter a desired y coordinate")<<std::endl;
std::cin>>yd;
while(std::cin.fail()){
std::cout<<("That is not a valid integer. Please enter a valid y co-ordinate")<<std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin>>yd;
}
struct xy{int x_received; int y_received;};
return xy{xd,yd};
}
We can see that the struct xy returns two values xd, yd in the above function start_end().
The following is my calling function:
int main(int argc, const char * argv[]) {
std::cout <<("A-Star-Algorithm for Project 2 obstacle map")<<std::endl;
int x_start = 0;
int y_start = 0;
int init_point = start_end();
return 0;
}
So when I try to store the return values xd, yd in the variable init_point, I get the error:
No viable conversion from 'xy' to 'int'
Since, I got this error I tried to write the receiving variable as a 2 - index array:
int init_point[2] = start_end();
When I try to do in this way, I get the following error:
Array initializer must be an initializer list
My exact question : What is the appropriate manner in which I have to receive the values xd and yd returned by function start_end() when it is called inside function int main() ?
You need to move your struct into a place that can be seen by start_end and main:
struct xy { int x; int y; };
xy start_end()
{
...
return { xd, yd };
}
int main()
{
}
Then you can either assign it with auto or use the type name xy:
int main()
{
auto xy1 = start_end();
xy xy2 = start_end();
}
Or you can use std::pair or std::tuple.
std::tuple is to your relief (live)
#include <iostream>
#include <tuple>
auto start_end() {
auto x = 1, y = 2;
return std::make_tuple(x, y);
}
int main() {
int x, y;
std::tie(x, y) = start_end();
std::cout << x << ' ' << y << std::endl;
}
I have a class with multiple methods defined. There is one method which simply returns a value from a member variable. There is another method which I would like to 'update' the returned value from the previous method, from inside this method.
Example: (assume declarations for X have already been made in a .hpp file)
A::A() {
X = 800; //constructor initialising x & y
Y = 1;
}
A::funcA() {
return Y;
}
A::funcB() {
if (x > y) {
//make funcA now return 2 ...
}
I can set Y to be the value I want perfectly, but how do I recall funcA to 'update' the value returned with the new value of Y I have set? When I try to call: funcA() == 2; It doesn't seem to update properly.
The simplest method would be to update the value of Y since that is beng returned.
A::A() {
X = 800; //constructor initialising x & y
Y = 1;
}
A::funcA() {
return Y;
}
A::funcB() {
if (x > y) {
Y = 2;
}
Your example lacks a few things like return values and what your return value would be if x
Just decide in funcA() what to return:
int A::funcA(){
if (x > y) {
return Y; // or return 2 or whatever, just an example
return X;
}
Or, have a special 'return value'
class A
{
private:
int X,Y,retA;
public:
A()
{
X = 800; //constructor initialising x & y
Y = 1;
retA=Y;
}
int funcA() {
return retA;
}
funcB() {
if (x > y) {
retA = 2;
}
}
}
You might even go for a pointer, if you want to switch between the two variables. This prevents you from copying the value but does not allow you to return a different value than one of the stored ones.:
class A
{
private:
int X,Y;
int* retA;
public:
A()
{
X = 800; //constructor initialising x & y
Y = 1;
retA=&Y;
}
int funcA() {
return *retA;
}
funcB() {
if (x > y) {
retA = &X;
//do NOT use retA = 2 here, that would be invalid
// *retA = 2 would be possible, but change either X or Y
}
else {
retA = &Y;
}
}
}
For example, we have this class:
class Coord
{
double x;
double y;
double z;
public:
Coord() { x = y = z = 0; }
void set(double xx, double yy, double zz)
{
x = xx;
y = yy;
z = zz;
}
void set_x(double xx) { x = xx; }
void set_y(double yy) { y = yy; }
void set_z(double zz) { z = zz; }
double get_x() { return x; }
double get_y() { return y; }
double get_z() { return z; }
};
On these 7 methods we can set and get x,y and z of a coordinate. I am interested in create less methods set() and get() where I can call something like that:
int main()
{
Coord c;
c.set_x(5); /* only set x */
c.set_y(6); /* or y */
c.set_z(7); /* or z */
c.set(1,2,5); /* or setting x, y and z */
c.get_x(); /* only get x */
c.get_y(); /* or y */
c.get_z(); /* or z */
}
If the Coord class is that simple, it could also be a struct.
Anyway you can write something like:
class Coord
{
public:
enum xyz {x = 0, y, z};
Coord() : vec{x, y, z} {}
template<xyz C> void set(double v) { vec[C] = v; }
template<xyz C> double get() const { return vec[C]; }
void set(double xx, double yy, double zz)
{
set<Coord::x>(xx);
set<Coord::y>(yy);
set<Coord::z>(zz);
}
private:
double vec[z + 1];
};
and use the class this way:
Coord c;
c.set<Coord::x>(5); /* only set x */
c.set<Coord::y>(6); /* or y */
c.set<Coord::z>(7); /* or z */
c.set(1,2,5); /* or setting x, y and z */
c.get<Coord::x>(); /* only get x */
c.get<Coord::y>(); /* or y */
c.get<Coord::z>(); /* or z */
getters and setters are meant to protect your data and provide encapsulation.
For example they allow you to add side effects to getting and setting operations (such as writing to a log), or allow you to catch invalid values early before they cause horrible problems later (For example preventing values greater than n being set).
Here's a brief and contrived setter example:
void set_x(int x)
{
// prevent an invalid value for x
if( x > 11 ) x = 11;
// set x
this.x = x;
// log the operation
log("user set x to {0}", x);
}
Assuming your c.set.x(5) example is not using some whacky preprocessor macros, it would require that the Coord class have a member variable called set with methods
x()
y()
z()
This would require just as much code as writing a set_x(), set_y() and set_z() method in your Coord class, but the methods would not belong to the class Coord, instead belonging to another class that is itself used as a member variable of Coord. Doing so would not really make any logical sense... the x, y, and z values belong to Coord and operations on them are operations on the Coord.
Furthermore the methods x() y() and z() would no longer obey the general principle of making methods verbs. Anyone reading the class with those methods would have no idea what function z() is supposed to do!
It would also create a refactoring nightmare: If for example in the future a business requirement appeared that meant no Coords could ever have values of x greater than 21 somone maintaining your code would have to change a class that is a member of Coord rather than the Coord class itself.
Encapsulation with getter and setter methods is often a really good idea and in C++ with the benefit of inlining it can even add no runtime overhead. But keep to the principle "Make everything as simple as possible, but not simpler." In other words get_x() and set_x() are widely understood, useful, easily refactored, convenient, self-documenting and performant... other approaches are likely to be less so.
First: Your usage of c.set.x would not work because you would call a public element set on your object c and where set has a public element x.
I find both classes lack standards of clean code and usual style of getter and setter - even without specifying any language.
A usual way would be to create the following:
class Coord
{
double x;
double y;
double z;
public:
Coord() {
x = 0;
y = 0;
z = 0;
}
Coord(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
void setX(double x) { this.x = x; }
void setY(double y) { this.y = y; }
void setZ(double z) { this.z = z; }
double getX() { return x; }
double getY() { return y; }
double getZ() { return z; }
};
Though some prefer to use m_x as setter variable parameter or any other convention.
Anyhow everyone would directly understand your code. Is able to set and get coordinate values for x, y, z and it would look pretty standard-default-behaviour if someone does following:
Coord P(10, 15, 20);
std::cout << P.getX() << " " << P.getY() << std::endl;
P.setX(-10);
P.setZ(40);
You've already gotten some good answers, but you could also use an enum if you really want a syntax with fewer setters and getters. The client syntax can get a little clunky and awkward, but it of course depends on what you're looking for!
#include <iostream>
class Coord {
public:
enum Axis {
X = 0,
Y,
Z,
NUM_AXES
};
// Using extended initializer lists (C++11)
Coord() : axes_{0, 0, 0} {}
Coord(double x, double y, double z) : axes_{x, y, z} {}
void set(Axis a, double d) {
axes_[a] = d;
}
double get(Axis a) const {
return axes_[a];
}
private:
double axes_[NUM_AXES];
// Copy constructor and assgn. operator included for good measure
Coord(const Coord &);
void operator=(const Coord &);
};
int main()
{
Coord c(1, 2, 3);
std::cout << "X: " << c.get(Coord::X) << std::endl;
std::cout << "Y: " << c.get(Coord::Y) << std::endl;
std::cout << "Z: " << c.get(Coord::Z) << std::endl;
c.set(Coord::Y, 4);
std::cout << "Y: " << c.get(Coord::Y) << std::endl;
return 0;
}
This strange code does exactly what you ask - just C++ fun. Don't do this!
#include <iostream>
using namespace std;
class Coord {
double x;
double y;
double z;
public:
class Setter {
public:
Setter(Coord& coord) : c(coord) {}
void x(double value) { c.x = value; }
void y(double value) { c.y = value; }
void z(double value) { c.z = value; }
void operator()(double x, double y, double z) { c.x = x; c.y = y; c.z = z; }
private:
Coord& c;
};
class Getter {
public:
Getter(Coord& coord) : c(coord) {}
double x() { return c.x; }
double y() { return c.y; }
double z() { return c.z; }
private:
Coord& c;
};
Setter set;
Getter get;
Coord() : set(*this), get(*this) { x = y = z = 0; }
friend class Setter;
};
int main()
{
Coord c;
cout << c.get.x() << " " << c.get.y() << " " << c.get.z() << endl;
c.set.x(1);
c.set.y(2);
c.set.z(3);
cout << c.get.x() << " " << c.get.y() << " " << c.get.z() << endl;
c.set(5, 6, 7);
cout << c.get.x() << " " << c.get.y() << " " << c.get.z() << endl;
return 0;
}
Output:
0 0 0
1 2 3
5 6 7
The more or less standard way to expose this, if validation is not a concern, is to return mutable references from the non-const accessor, and values from the const one. This allows you to separate the interface from storage, while not making the syntax too heavy.
private:
double m_x, m_y, m_z;
public:
double & x() { return m_x; }
double & y() { return m_y; }
double & z() { return m_z; }
double x() const { return m_x; }
double y() const { return m_y; }
double z() const { return m_z; }
This will allow c.x() to obtain the value of the x coordinate whether the Coord object is const or not, and allows setting the value using the syntax c.x() = value.
In the interest of completeness, you can get exactly the syntax you want using the following code, but I would strongly recommend against it. It is a lot of extra code, provides no real benefit, and creates a syntax that is uncommon and most programmers will not find it intuitive.
The technique creates two nested classes getters and setters and exposes instances of them as public members of Coord.
This is provided as an example of how to achieve the result you asked for, but I do not recommend this approach.
class Coord
{
private:
double x, y, z;
public:
Coord();
Coord(double, double, double);
class setters {
friend class Coord;
private:
explicit setters(Coord &);
public:
setters(setters const &) = delete;
setters & operator=(setters const &) = delete;
void x(double) const;
void y(double) const;
void z(double) const;
private:
Coord & coord;
};
friend class setters;
class getters {
friend class Coord;
private:
explicit getters(Coord const &);
public:
getters(getters const &) = delete;
getters & operator=(getters const &) = delete;
double x() const;
double y() const;
double z() const;
private:
Coord const & coord;
};
friend class getters;
setters const set;
getters const get;
};
Coord::Coord() : x(0), y(0), z(0), set(*this), get(*this) { }
Coord::Coord(double px, double py, double pz) : x(px), y(py), z(pz), set(*this), get(*this) { }
Coord::setters::setters(Coord & c) : coord(c) { }
void Coord::setters::x(double px) const {
coord.x = px;
}
void Coord::setters::y(double py) const {
coord.y = py;
}
void Coord::setters::z(double pz) const {
coord.z = pz;
}
Coord::getters::getters(Coord const & c) : coord(c) { }
double Coord::getters::x() const {
return coord.x;
}
double Coord::getters::y() const {
return coord.y;
}
double Coord::getters::z() const {
return coord.z;
}
(Demo)
Actually the function can be reduce based on your requirement as follows,
class Coord
{
double x;
double y;
double z;
public:
Coord() {
x = 0;
y = 0;
z = 0;
}
void GetValues(double* x=NULL, double* y=NULL, double* z=NULL);
void SetValues(double x=0, double y=0, double z=0)
/* You can use constructors like below to set value at the creation of object*/
Coord(double x, double y, double z)
{
this.x = x;
this.y = y;
this.z = z;
}
/*You can set the values of x, y & z in a single function as follows. It can be used at any time without restriction */
void SetValues(double x, double y, double z)
{
if(x > 0) //It is optional to use condition so that you can update any one variable aloen by sending other two as ZERO
{
this.x = x;
}
if(y > 0)
{
this.y = y;
}
if(z > 0)
{
this.z = z;
}
}
/*You can Get the values of x, y & z in a single function as follows. Pass By Reference id the concept you need */
void GetValues(double* x, double* y, double* z)
{
if(x != NULL) //It x is not null.
{
x = this.x;
}
if(y != NULL)
{
y = this.y;
}
if(z != NULL)
{
z= this.z;
}
}
};
while calling you can call like the following,
SetValues(10, 20, 0); //To set x and y values alone.
double x1 = 0;double y1 = 0;double z1 = 0;
GetValues(&x1, &y1, &z1)//It will return the values x1 y1 and z1 as 10, 20 & 0
You cannot do exactly what you want.
In
c.set.x(5); /* only set x */
the c.set subexpression is retrieving a field set from c (unless set is a #define-d macro, but that would be silly).