int calculateX()
{
int x;
cout<<"Enter value for x: ";
cin>>x;
return x;
}
int anotherFunction()
{
/////
}
int main()
{
calculateX();
anotherFunction();
return 0;
}
This is an example on a code. How do can I possibly use the input from the user in the calculateX() function into the function anotherFunction() ?
You have to use function parameters:
int calculateX()
{
int x;
cout<<"Enter value for x: ";
cin>>x;
return x;
}
int anotherFunction(int x)
{
/////
}
int main()
{
int x = calculateX();
anotherFunction(x);
return 0;
}
what you need is either a pass by value , which is already answered or a global variable like this
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int anotherFunction()
{
cout << g;
}
int main () {
// Local variable declaration:
int a, b;
a = 10;
b = 20;
g = a + b;
anotherFunction();
return 0;
}
A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
You must declare the variable x global (outside the calculateX() function), so that anotherFunction() can see it. If you define the variable x inside the calculateX() function, it will be deleted after exiting the function.
int x;
int calculateX()
{
cout<<"Enter value for x: ";
cin >> x;
return x;
}
int anotherFunction()
{
/////
}
int main()
{
calculateX();
anotherFunction();
return 0;
}
Function generally has return type before it's name. For Example :
int calculateX() {
int x;
cout<<"Enter value for x: ";
cin>>x;
anotherFunction(x)
return x;
}
int is here return type.And you are calling two functions from your main function. calculateX has a variable of type int named x. So, you can't access x from outside of calculateX scope. But you can return it to your main function and store it in a different variable so that It becomes available in main function. Once It becomes available, you can send it as argument to another function . In your case It should be like this :
int anotherFunction(int valueFromMain)
{
std::cout << valueFromMain << std::endl;
}
int main(){
int returnedFromCalculateX = calculateX(); //You have returned value available on main Function
anotherFunction(returnedFromCalculateX); //Send It to anotherFunction(pass by value)
return 0;
}
You can also send the value as a reference. That needs a bit higher understanding. Please Check : https://www.w3schools.com/cpp/cpp_function_reference.asp for more details.
Related
So there's this code am trying to understand:
#include <iostream>
using namespace std;
int x = -2;
int h(int &x) {
x = 2 * x;
return x;
}
int g(int f) { return x; }
int &f(int &x) {
x += ::x;
return x;
}
int main() {
int x = 6;
f(::x) = h(x);
cout << f(x) << endl;
cout << g(x) << endl;
cout << h(x) << endl;
return 0;
}
Output:
24
12
48
I understood the function of the scope resolution operator (::), which is to use the global int x, but the part that i don't understand is this part: f(::x) = h(x); and this one: int g(int f){return x;}
So what am trying to understand is what happens step by step when these instructions get executed.
The line
f(::x) = h(x);
is equivalent to
operator=(f(::x), h(x));
First, one of the functions f or h are called and the returned value is passed to operator=. Then the other function is called and the returned value is passed to operator=. The order is irrelevant because in either case f changes the value of global x to -4 and returns a reference to it and h changes local x (local in main) to 12 and returns its value. Then the value 12 is assigned to global x.
The line
int g(int f) { return x; }
defines a function that returns the value of global x.
Maybe using different variable names helps understanding:
#include <iostream>
using namespace std;
int globalX = -2;
int h(int &hX) {
hX = 2 * hX;
return hX;
}
int g(int f) { return globalX; } // f is unused
int &f(int &fX) {
fX += ::globalX;
return fX;
}
int main() {
int mainX = 6;
f(::globalX) = h(mainX);
cout << f(mainX) << endl;
cout << g(mainX) << endl;
cout << h(mainX) << endl;
return 0;
}
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))
After reading StackOverflow's discussions and implementing some advices, I have these pieces of code intended just to test the behavior of static members of a class.
Here is the header, which has the class declaration:
class OurClass
{
private:
static int x, y;
public:
static void setVals(int valx, int valy);
static int getValx();
static int getValy();
static void initialize();
};
And here is the cpp file, which has the definition of these members as well as the main() function:
#include <iostream>
#include "OurClass.hpp"
using namespace std;
void OurClass::initialize()
{
static int x = 0;
static int y = 0;
}
void OurClass::setVals(int valx, int valy)
{
static int x = valx;
static int y = valy;
}
int OurClass::getValx()
{
static int x;
return x;
}
int OurClass::getValy()
{
static int y;
return y;
}
int main(void)
{
OurClass::inicializa();
cout << "Provide x and y..." << endl;
OurClass::setVals(cin.get(), cin.get());
cout << "Value of x: " << OurClass::getValx() << endl;
cout << "Value of y: " << OurClass::getValy() << endl;
return 0;
}
So, assuming that a static variable exists for the class, and that static functions only access static variables, I was expecting that x and y would have the values that we read from the keyboard with the setVals() call in main(). But when printing their values in the couts, they still have the value we assigned in the initialize() function (which BTW was another suggestion I got here, that is, initialize a static variable in a method).
I am also unable to refer directly to the variables by OurClass::x or y even if I make them public.
Do you guys know why?
First you need to access your local class's static variable instead declaring new method local variables in each method. Check below.
class Out {
private:
static int x, y;
public:
void set(int x, int y);
int getSum();
};
int Out::x = 0;
int Out::y = 0;
void Out::set(int x, int y) {
Out::x = x;
Out::y = y;
}
int Out::getSum() {
return Out::x + Out::y;
}
Instead of setting values of existing variables this code creates new local static variables. Fix:
void OurClass::initialize()
{
x = 0;
y = 0;
}
void OurClass::setVals(int valx, int valy)
{
x = valx;
y = valy;
}
int OurClass::getValx()
{
return x;
}
int OurClass::getValy()
{
return y;
}
And add the definitions of those static variables in a .cc file (not header):
int OurClass::x;
int OurClass::y;
Imagine I have a class and it has a private value for example this value name is a, then I set it's value to 10.
How I can access to this variable with its value (10) in another class?
(I do not want to use friend function and friend class)
a.h
#include <iostream>
using namespace std;
static int s=0;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class a
{
private:
public:
void sets(int );
};
a.cpp
#include "a.h"
void a::sets(int y){
cin >> y;
s=y;
}
main.cpp
#include"a.h"
int main()
{
int i=0;
int q;
a a1;
a1.sets(q);
cout << s+1 << endl;
for (i=1; i<5; i++){
if (s == i) cout << "ok";
}
}
If you do not want to use friendship, add a public interface to this variable (setter and/or getter class members).
Either make the variable public or add a function to get the value that returns it, like int getA() const { return a; } .
Use a private member s in your class a instead of a global variable, and access it via public Getter function GetS
Example:
#include <iostream>
using namespace std;
class a
{
private:
int s;
public:
void SetS() { cin >> s; }
int GetS() const { return s; }
};
int main()
{
a a1;
a1.SetS();
int s1=a1.GetS();
cout << s1+1 << endl;
for (int i=1; i<5; i++){
if (s1 == i) cout << "ok";
}
}
I'm new in C++
I try to pass array as parameters I can't find a solution.
Here's my code :
My Header code
autobus.h
#ifndef autobus_H
#define autobus_H
#include <iostream>
using namespace std;
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int, int);
};
#endif
Bus.cpp
#include <iostream>
#include "autobus.h"
autobus::autobus(){
int i,j;
for (i=0;i<2;i++) {
for (j=0;j<40;j++)
placeautobus[i][j] = 0;
}
};
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "autobus.h"
using namespace std;
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
system("PAUSE");
return EXIT_SUCCESS;
}
Everything works, but when I add this line in my main.cpp :
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
I have an error, I try many things.
I just want to call my function calculdesplaces with the variable : choixautobus having array placeautobus.
Can someone know how to do this.
thanks
Like others have said already, the code you have now shouldn't compile right now because of the declaration and definition mismatch for calculdesplaces.
You shouldn't need to pass the placeautobus array at all since it is a member of the autobus class. Just delete your 2nd argument from calculdesplaces and you should be able to do what you want.
int autobus::calculdesplaces(int typeautobus){
int placenumero;
for (int place = 0; place < 40; place++){
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
In your class declaration, you need to specify the correct array pointer type for the second parameter of calculdesplaces():
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus, int (*placeautobus)[40]);
int placeautobus[2][40];
};
This declares, that you are passing a pointer to an array of 40 int elements. This is precisely the type to which the 2D array int placeautobus[2][40]; decays when you use its name: When you mention the name of an array, the array name decays into a pointer to its first element. In the case of an array of type int ()[2][40], that is a pointer to the first line array (type is int (*)[40]).
Note that the parentheses in int (*placeautobus)[40] are very important: the array subscript operator [] has a higher precedence than the dereferencing operator *, so int (*placeautobus)[40] means something very different from int* placeautobus[40].
I have also taken the liberty of including the variable names in the method declaration, this provides essential information to the reader, even though the compiler ignores it.
In the implementation of calculdesplaces(), you can access the argument array precisely the same way as you can access any 2D array:
int autobus::calculdesplaces(int typeautobus, int (*placeautobus)[40]) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
Now you can easily call your function by just passing the array:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus);
system("PAUSE");
return EXIT_SUCCESS;
}
Note:
The above only fixes the symptoms, not the disease. The actual problem is, that the design of the class itself is flawed. Data members should generally not be public, and methods should work on the data of the object on which they are called, instead of relying on getting parts of the object passed in via additional arguments. So, the class definition should look like this:
class autobus{
public :
autobus();
void affichageTicket();
int calculdesplaces(int typeautobus);
private:
int placeautobus[2][40];
};
The definition of calculdesplaces() doesn't change that much, it just does not shadow the already available array member with a function argument:
int autobus::calculdesplaces(int typeautobus) {
int placenumero;
for (int place = 0; place < 40; place++) {
if ( placeautobus[typeautobus][place] ==0) {
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
}
}
return placenumero;
}
And you don't need to "grab into the object" in main(), the array is implicitly passed via the this pointer:
int main() {
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces(TypeAutobus);
system("PAUSE");
return EXIT_SUCCESS;
}
You haven't mentioned what the error it. But I think this it the issue:
What is the data type of second argument in calculdesplaces function declaration:
int calculdesplaces(int, int);
It is: int
What is the data type of placeautobus[2][40] in calculdesplaces function definition:
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){ ... }
It is: int*
What is the data type of placeautobus[2][40] in calculdesplaces function call:
choixautobus->calculdesplaces(TypeAutobus, choixautobus->placeautobus[2][40]);
Looking at class autobus { ... }, it is: int
So there is mismatch between the datatype used in function declaration, definition and call. Try solving this.
The code should not be compiled.
The member function declaration of calculdesplaces
int calculdesplaces(int, int);
does not coinside with its definition
int autobus::calculdesplaces(int typeautobus, int *placeautobus[2][40]){
The type of the second parameter differs.
As for the error message then the function should be called as
choixautobus->calculdesplaces( TypeAutobus, choixautobus->placeautobus );
Take into account that the function has a bug. You pass to the function as the first argument either 1 or 2 and use these values as indices of the array while the valid indices are 0 and 1.
Also the function does not need to have the second parameter because it deals with the data member
int placeautobus[2] [40];
So I would define the class and member functions the following way
class autobus{
public :
int placeautobus[2] [40];
autobus();
void affichageTicket();
int calculdesplaces(int);
};
#include <iostream>
#include "autobus.h"
autobus::autobus() : placeautobus {}
{
}
void autobus::affichageTicket()
{
}
int autobus::calculdesplaces( int typeautobus )
{
int placenumero = 0;
for (int place = 0; place < 40; place++)
{
if ( placeautobus[typeautobus - 1][place] == 0 )
{
placenumero = place+1;
cout <<"Places : "<< placenumero <<endl;
break;
}
}
return placenumero;
}
Though I do not understand what you return from the function.:)
Also you could specify the initialization of the array inside the class definition
class autobus{
public :
int placeautobus[2] [40] = {};
//...
In this case the main can look as
int main()
{
int TypeAutobus;
autobus *choixautobus = new autobus();
cout << "1 for smoking bus" << endl;
cout << "2 for non-smoking bus" << endl;
cin >> TypeAutobus;
choixautobus->calculdesplaces( TypeAutobus );
system("PAUSE");
return EXIT_SUCCESS;
}