In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.
In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.
int foo(int a, int b) {
int c, d;
while ( etc. ) {
c = arithmetic_for_c;
d = arithmetic_for_d;
e = c + d;
}
return e;
}
int bar(a, b) {
cout << e;
cout << c << d;
}
This example is very simple, but you get the idea.
I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.
I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.
The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.
Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.
Thoughts?
Thank you!
Unless you want to go really fancy (probably not within your reach, yet), foo() has to help bar() a little.
Since you want to show the end result first, then the intermediate data later, you will have to find some way of storing the intermediate states. You could do so, using arrays or lists and push the intermediate values into them.
But another, probably shorter option is, to just store the intermediate output.
You know how to use std::cout by now, which prints output to the console.
It is of type std::ostream. And next to output to a console (or file etc.), the c++ standard library also allows to output to a string.
So, for your use case to work, you create such a string stream, then call bar and give it as output stream the string stream.
At the end of your calculations, you call bar with the regular output stream to print the end result, then, you output the string of the string stream to the regular output stream.
It sounds more convoluted, than it actually is, if you see it in code:
#include <iostream>
#include <sstream>
void bar(int a, int b, int c, int d, int e, std::ostream& os) {
os
<< "a: " << a
<< " b: " << b
<< " c: " << c
<< " d: " << d
<< " e: " << e
<< std::endl;
}
int foo(int a, int b, std::ostream& os ) {
std::ostringstream ossteps;
int c= 0;
int d= 1;
int e= 42;
while (c < 10) {
bar(a,b,c,d,e,ossteps);
c++;
d += c*c;
e = (a * b) - d;
}
bar(a,b,c,d,e,os);
os << ossteps.str();
return e;
}
int main (int argc, const char* argv[]) {
int efinal = foo(1,2, std::cout);
return 0;
}
If I'm not mistaken, this is not really possible in C++, as the variables are declared in the scope of the function foo, and cannot be accessed from a different scope. But you can always use something like this:
Pass by reference (out parameters):
#include <iostream>
// Declaring bar earlier as it has to be accessed by foo
int bar(int& c, int& d) {
int e = 0; // Declaring and initializing variable e
int count = 0;
// Loop
while (count < 10) {
c++;
d += 2;
e = c + d;
count++;
}
return e; // Return variable e
}
int foo(int a, int b) {
int c, d;
c = a, d = b; // setting c = parameter a, d = parameter b
int e = a + b;
std::cout << c << d << std::endl; // Printing variables c and d
std::cout << e << std::endl; // Printing variable e
e = bar(c, d); // Calling bar function. Also this function increments c by 10 and d by 20.
std::cout << c << d << std::endl; // Printing variables c and d
std::cout << e << std::endl; // Printing variable e
return e; // Return variable e
}
int main() {
foo(10, 20); // Calling function 'foo'
}
This is just an example.
The CPU is performing one thread at a specific time. So it can only perform the code in function foo or the function bar, but never both. The scope of the variables in the function are called local or auto variables. They are valid only in the context of the execution of the function. At language level you will say they go out of scope at the closing } bracket. Technically, the memory for the variable is allocated temporarily while entering the function and automatically released on exit. It's just a memory location on the stack. The live time of the variable ends at the end of scope.
So, you must always look at the scope of a variable. You can't access anything temporarily allocated on a different function's stack. The game changes if one function calls another. You can pass a reference from the calling function to the called function, but not the other way.
int foo(int a, int b, int& c, int& d) {
while ( etc. ) {
c = arithmetic_for_c;
d = arithmetic_for_d;
e = c + d;
}
return e;
} // scope of the reference c and ends here,
// but not the scope of the referenced variables.
int bar(a, b) {
int c, d;
// here you define the role of calling function and called function.
int e = foo(a, b, c, d);
cout << e;
cout << c << d;
} // scope of c and d ends here.
Related
here is the question I have, i got this code and it needs to write out 2, 5, 1, for the variables a, b, c.
But the catch is the main should not change, only the function. I managed to change the b to 5, but I really don't know how to change a to 2 without using pointeres.
Here's the code:
#include <iostream>
using namespace std;
int& function(int a, int* b, int c) {
return *b;
}
int main()
{
int a, b, c;
a = b = c = 1;
function(a, &b, c) = 5;
cout << a << " , " << b << " , " << c << endl;
return 0;
}
Every help will be highly appreciated.
I tried using pointers but the main should not be changed.
If you can't modify the function signature, then it is a terrible question. As written, it is impossible. The compiler is allowed to assume a will stay 1.
There's a kind of professors I've seen that would want you to turn in:
int& function(int a, int* b, int c)
{
b[1] = 2;
return *b;
}
But this relies on UB, a specific architecture and disabling optimization. https://godbolt.org/z/rc1d9oqab
If you are allowed to modify the function signature, yeah, then pass a reference for a.
//libraries
#include <iostream>
//standard namepace
using namespace std;
int Car() {
int a;
int b;
cout << "Fuel Tank" << endl;
cin >> a;
cout << "MPG" << endl;
cin >> b;
return a, b;
}
int main() {
int a;
int b;
a,b = Car();
cout << "Print Values " << (a,b); // <--- Line 25
return 0;
}
Let's say you put 10 and 15 as the first and second input. Why is 15 the only variable to print in the cout statement on line 25.
That's not how C++ works.
You need:
std:: pair<int, int> Car() {
...
return {a, b};
}
auto [a, b] = Car();
std::cout << a << ", " << b;
What you have:
int Car()
Car is a function which returns 1 int.
return a, b;
Here you have the comma operator which evaluates every argument and discards all but the last one. So it returns b.
a, b = Car();
(a, b)
Again the comma operator. a is discarded and b is assigned. Then a is discarded and b is printed.
Unlike Python, C++ does not have a built in notion of a tuple. Your Car function is declared to return a single integer, and so one integer you will get. An alternative is to use std::pair<int, int> in #include <utility> like so:
std::pair<int, int> Car() {
// ...
return std::make_pair(a, b);
}
I assume the program compiles because in C/C++, the comma separated expression list as you wrote is evaluated in order and only the last expression or item in that list is returned. So your first Car() function returns the last integer b, and you only initialize b in your assignment in main() to that other b. Likewise, your cout only prints b, hence 15.
What I would recommend doing is making the function a void and passing the variables by reference. When you pass the variables by reference, you can change their value in the function and they will not be lost due to scope. This is because passing by reference references the location in memory where that variable is stored, instead of creating a copy like passing by value does (which you did).
#include <iostream>
using namespace std;
void car(int &a, int &b); // function prototype calling for a and b to be passed by
// reference
int main()
{
int a = 0;
int b = 0;
car(a, b);
cout << "Print Values " << a << " " << b;
return 0;
}
void car(int &a, int &b)
{
int temp = 0;
cout << "Fuel Tank" << endl;
cin >> a;
cout << "MPG" << endl;
cin >> b;
}
As you see, instead of returning values, the function changes the values of the variables by accessing their location.
Edit: Typically, functions will go below main and you have prototypes for the functions above main (as seen in my example).
Another thing, you named the function, "Car();". Typically, functions start with the first word as a lowercase letter with the following words capitalized. This makes it easier to not confuse them with constructor function names for classes, in which the first letter of the first word is usually capitalized.
Say I declare a variable in one function like so:
void i() {
int c;
}
how would I be able to do this in a different function?
void j() {
cout << c << endl;
}
Lets start with the basics:
in C++, default storage class of variables is auto.
What this means is that variables declared inside a block will only be available inside that block after you declare them.
a block is marked with the curly braces (loops, if statements, functions, etc)
void i() {
//c is not declared here and is unavailable
int c;
//c is available
for(int i=0; i<2; i++)
{
//c is also available here, because it is declared in larger scope
}
}
//c is not recognized here because it is declared only inside the scope of i()
void j()
{
int c; //this is variable c. it has nothing to do with the c that is declared in i()
for(int i=0; i<2; i++)
{
int d; //this variable gets created and destroyed every iteration
}
//d is not available here.
}
By default, a variable that is declared inside the body of a function, will live only inside that function scope after the point of declaration.
In your question you have not described how you want the two functions to communicate, thus it is difficult to point to a suitable approach.
If you want to pass the same value between functions you should read into argument passing and function return values. There is another way which is global variables, not recommended unless absolutely needed, but definitely something you need to learn.
void j(const int c)
{
std::cout << c << std::endl;
}
Then just call it from your function using:
j(c);
The best approach depends on what you actually do with c. Namely if c is not unique to an invocation of i() then you can use a global variable to get access it anywhere:
int c;
void i(){
c = c++; //uses c, pun intended
}
void j(){
cout << c << endl;
c++; //can change c
}
If a unique c is used every time i()is called, then you can define it in i() and have to pass it to j() from within i(), otherwise j() does not know where c is:
void i(){
int c;
j(c);
}
void j(int c){
cout << c << endl;
c++; //cannot change c in i()
}
Note that above c in i() and c in j() are not the same variable. If you change c in j() it will not be changed in i(), where as with the global approach it would be.
If want the variable to be unique to i() but accessible to j() you would instead pass the variable either by a pointer(not shown) or refence(shown below):
void i(){
int c=0;
j(c);
}
void j(int &c){
cout << c << endl;
c++; //can change c in i()
}
Note: The terminology here is rather casual, I didn't even use the word scope which you may want to learn more about.
The variable c wouldn't exist in the context where j is called, so you'd have to pass it on as a global variable or a return value.
int i(){
int c = 2;
return c;
}
int i() will return c, which can be passed on to other constructors.
void j(const int c){
std::cout << c << std::endl;
}
Or rather, call i inside of j.
void j(){
int cr = i();
std::cout << cr << std::endl
}
I am completely new to structs and user defined datatypes, and i was trying to create a function that returns a struct:
The problem is highlight by the comment:
#include <iostream>
using namespace std;
struct num {
int n[2];
};
num func( num x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
return x;
}
int main() {
int x,y;
num s1;
cout << "enter: ";
cin >> x >> y;
func(s1,x,y);
cout << s1.n[0] << "\n" << s1.n[1]; // THIS GIVES ERROR
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1]; // THIS DOENST GIVE ERROR
return 0;
}
I understand that second method makes sense and returns the struct variable. then putting a dot addresses the inner variable of struct.
But i dont understand why first method fails, or gives odd output. The function has done its job, ie made s1.n[0] = x + y and s1.n[1] = x*y
Now, printing s1.n[0] should print x + y only. How can we check and correct the internal workings of the function?
You have to assign the returned value to the structure object in main
s1 = func(s1,x,y);
Inside the body the function deals with a copy of the original object. It does not change the original object because it is passed by value.
Another approach is to pass the structure by reference
void func( num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
In this case in main you could just write
func(s1,x,y);
Or you could use even so-called C approach of passing by reference
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
and call it like
func( &s1, x, y );
As for this statement
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1];
then you access data members of two temporary objects returned by the two calls of the function. After executing this statement these temporary objects will be deleted.
It looks like you are never assigning the return value of func(). Your function returns the struct, but you are never assigning it. To fix this, you should be able to simply say: s1 = func(s1,x,y); This will assign the modified version of the struct to the s1 variable.
Alternatively, you could rewrite func() to accept a pointer to the struct. This would allow you to modify the struct without having to return it:
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
Then you would just change your call to func() to say: func(&s1, x, y);
You are not passing your struct by reference, hence the result. Try the following:
void func(num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
There's no need for the function to return anything since your struct is passed by reference and it will be changed anyway. Void would fit better.
This is because you have passed the struct by value while your intentions look like you want to pass by reference.
Check this link : http://courses.washington.edu/css342/zander/css332/passby.html
num func( num &x, int a, int b)
should fix your problem
I tried asking before but I wasn't very clear so I'm re-asking it.
I want to have a variable that depends on the value of another variable, like b in this example:
int main(){
int a;
dependent int b=a+1; //I'm just making this up
a=3;
cout << b; //prints 4
a=4;
cout << b; //prints 5
}
Of course, this does not exist in C++, but this is what I want.
So instead I tried making a function:
int main(){
int a;
int b(){ return a+1; } //error
a=3;
cout << b(); //would print 4 if C++ allowed nested functions
a=4;
cout << b(); //would print 5 if C++ allowed nested functions
}
The above doesn't work because C++ doesn't allow nested functions.
I can only make functions outside of main(), like this:
int b(){
return a+1; //doesn't work because a is not in scope
}
int main(){
int a;
a=3;
cout << b();
a=4;
cout << b();
}
But this does not work because a is not in the same scope as b(), so I would have to pass a as a parameter and I don't want to do that.
Are there any tricks to get something similar to a dependent variable working in C++?
What you need is a closure. If you can use C++ 0x features, you are in luck. Otherwise, you can define one manually:
#include <iostream>
using namespace std;
struct B
{
const int & a;
B(const int & a) : a(a) {}
// variable syntax (Sean Farell's idea)
operator int () const { return a + 1; }
// function syntax
int operator () () const { return a + 1; }
};
int main()
{
int a;
B b(a);
a = 3;
cout << b << '\n'; // variable syntax
a = 4;
cout << b() << '\n'; // function syntax
}
You can also define B inside main, but some compilers would not like it.
The C++ 0x lambda syntax looks like this:
auto b = [&]() { return a + 1; }
The [&] means that the lambda captures local variables by reference.
If you're using C++0x (GCC 4.5+, Visual C++ 2010), you can use lambdas:
int a = 5;
auto b = [&a]{ return a + 1; };
std::cout << b() << std::endl;
Depending on what you're doing, though, there are probably cleaner solutions - possibly some variation of the classic "method that takes in 'a' and returns 'b'"
You could define a class that had a member a, and then a function b() that returned the value of a+1. A basic implementation would be something like:
class Dependent {
public:
Dependent(void) { m_value = 0; }
void set(int value) { m_value = value; }
int b(void) { return(m_value + 1); }
private:
int m_value;
};
int main(){
Dependent a;
a.set(3);
cout << a.b();
a.set(4);
cout << a.b();
}
You could add operator overloading as appropriate to make it work more like normal integers if you so desired.
This is possible if you use lambda functions (c++0x), because they can capture local variables.
Example:
int main()
{
int a;
auto f = [&] () -> int { return a + 1; };
a = 3;
std::cout << f() << std::endl;
a = 4;
std::cout << f() << std::endl;
return 0;
}
Result:
4
5
(See http://ideone.com/MlzX7 for proof)
A simple approach is to use pre-processor macros, nothing C++ specific about it though:
#define b ((a)+1)
int main(){
int a;
a=3;
cout << b;
a=4;
cout << b;
}
#undef b
Are you OK using C++0x ? if yes,
int main()
{
int a = 10;
auto b = [&a]() -> int { return a + 1; };
cout << b() << endl;
}
Since, it is not tagged with c++0x, you can use nested classes instead of nested functions. This column from Herb sutter would help you for existing c++. http://www.gotw.ca/gotw/058.htm
The above doesn't work because C++ doesn't allow nested functions.
You can simulate that using nested structure. In C++0x you can make use of lambda function, which provides the same means of function inside function.
Define a class called LinkedInt or something that behaves like an int, but has a RelatedTo relationship on itself and an additional member that is a function pointer to the function to evaluate when computing the integer's value. Pretty straightforward. Let me know if you need some pointers on the coding.
The short answer is that OOP is more than enough to bury this problem.
I want to have a variable that depends on the value of another
variable, like b in this example:
I see you just need a reference variable:
int a;
int &b =a;
a=10;
cout << b; // 10
Why C++0x lambdas do come for this, I dont understand.