Only one variable is printing C++ - c++

//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.

Related

Using variables in a function from another function

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.

How to access int a declared in main in another function?

#include <iostream>
using namespace std;
void b();
int main() {
int a = 10;
b();
}
void b() {
int a;
cout<<"Int a="<<a;
}
I am looking to print the value of a in the main scope using a function, with my current code, it prints Int a=0. How can I achieve this?
Don't declare an entirely new a inside b().
Pass the a from main to b() and then print that.
For example:
#include <iostream>
void b(int whatever_name_you_want_here);
int main()
{
int a = 10;
b(a);
}
void b(int whatever_name_you_want_here)
{
std::cout << "Int a=" << whatever_name_you_want_here;
}
//Change your code to the following and it will give you the result you're looking for.
On your code there is no way to pass int a on the main to b(); unless b accepts a parameter of the type you want the function to output.
#include<iostream>
void b(int);
int main()
{
int a = 10;
b(a);
}
void b(int a){
std::cout << "int a=" << a;
}
I guess the main problem is not being aware of something very important which is called scope! Scopes are usually opened by { and closed by }
unless you create a global variable, it is only known inside the scope it has been introduced (declared).
you declared the function b in global scope :
void b();
so after this every other function including main is aware of it and can use it.
but you declared the variable a inside the scope of main:
int a = 5;
so only main knows it and can use it.
Please make note that unlike some other programming languages, names are not unique and not every part of the program recognize them in c and c++.
So the part:
void b() {
int a;
does not force the function b to recognize the a which was declared in main function and it is a new a.
so to correct this mistake simply give the value or reference of variable a to function b :
#include <iostream>
void b(int&);
int main() {
int a = 10;
b(a);
}
void b(int& a) {
std::cout << "Int a=" << a << std::endl;
}
please also note that the a as argument of the function b is not the same a in the function main.
The final tip is every argument for functions is known inside that function scope as it was declared inside the function scope!
What you want to achieve requires you to pass a value to a function. Let me give you an example on how to do that.
#include<iostream>
void print_value(int value){
std::cout << "Value is: " << value << '\n';
}
int main(){
int a = 5;
print_value(a);
return 0;
}
The only thing you are missing in your program is the parameter. I won't bother explaining the whole thing over here as there are numerous articles online. Here is a straightforward one.
Refer to this to understand how functions work in C++
Use pass by reference to access a variable which is declared in one function in another.
Refer the below code to understand the use of reference variable,
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
#include <iostream>
using namespace std;
void displayValue(int number) {
cout<<"Number is = "<<number;
}
int main()
{
int myValue = 77;
displayValue(myValue);
return 0;
}

Does a destructor call itself when an object passed as a parameter goes out of scope?

I am using a static variable to keep track of the number of instances of an object. I am getting some unpredictable behavior with the following code:
#include <iostream>
using namespace std;
class comp{
private:
int a;
int b;
public:
friend comp &operator+(comp, comp);
static int c;
comp(int, int);
comp();
~comp();
int getA();
int getB();
void print() const;
};
int comp::c = 0;
comp::~comp() {
c--;
cout << "destroying comp of " << a << ", " << b << ", count after decrement is " << c << endl;
}
comp &operator+(comp A, comp B){
comp C = comp(A.a + B.a, A.b + B.b);
cout << "in +, count is " << comp::c << endl;
return C;
}
comp::comp(int A, int B){
a = A;
b = B;
c++;
}
comp::comp(){
a = 0; b = 0; c++;
}
int comp::getA(){
return a;
}
int comp::getB(){
return b;
}
void comp::print() const{
cout << a << ", " << b << endl;
}
int main()
{
cout << comp::c << endl;
comp A = comp(3,4);
cout << comp::c << endl;
comp B = comp(4,5);
cout << comp::c << endl;
A + B;
A.print();
B.print();
cout << "About to exit main, c is: " << comp::c << endl;
return 0;
}
Output is this:
0
1
2
in +, count is 3
destroying comp of 7, 9, count after decrement is 2
destroying comp of 3, 4, count after decrement is 1
destroying comp of 4, 5, count after decrement is 0
3, 4
4, 5
About to exit main, c is: 0
destroying comp of 4, 5, count after decrement is -1
destroying comp of 3, 4, count after decrement is -2
This behavior is being caused by the line
A + B;
My best guess as to what is happening is that when the objects are passed in as parameters to a function, the constructor is not being called (so c is not being incremented), but when the function goes out of scope, the destructor is called. This leads to a net loss in count.
However, the overloaded operator+ passed variables by references. Wouldn't this prevent the parameters from going out of scope and the destructor being called?
The output is the same regardless of whether the overloaded + operator is declared as:
friend comp &operator+(comp, comp);
or
friend comp operator+(comp, comp);
This leads me confused as to why and how the destructor is being called.
One last question: is it good practice, when using overloaded operators, to pass by reference rather than by value? If so, why?
Thanks!
EDIT:
It appears as if I was confusing the syntax a bit. I thought that
friend comp &operator+(comp, comp);
was passing the parameters by reference instead of
friend comp operator+(comp&, comp&);
Excuse my noobish question, but could someone explain what the "&" operator does before a function name? If I understand correctly, "&" is the reference operator and gives the address given a variable. However, if one would want to return a reference, the "*" operator would be appropriate. For instance:
int *a()
The above function signature returns a memory address that points to an int.
int &a()
What would that function signature return?
You are not accounting for objects created by default, compiler generated copy constructor. Define one, count the objects created there and the math will work out.
Your problem is that when you get objects as parameters, you make a copy of them. And that's that copy which will be destructed at the end of the scope.
In order to avoid that, you should pass them by reference:
comp operator+(comp& a, comp& b);
The & in the return type is of the return value, i.e. C in your code. And this is bad, because you send a reference to a variable created locally, which will be destroyed at the end of the scope.

Calling Class Constructor in Member Function

Here's a program, where I am trying to call the class constructor multi::multi(int, int), in the function void multi::multiply(). The output is
30
30
instead of expected
30
25
Why?
#include <iostream.h>
class multi{
private:
int a;
int b;
public:
multi(int m, int n){
a = m;
b = n;
}
void multiply(){
cout << "\n\n" << a*b;
multi (5, 5);
cout << "\n" << a*b;
}
};
main(){
multi x(5,6);
x.multiply();
return 0;
}
multi (5, 5);
It creates a temporary object, and gets destroyed by the end of the full expression. It doesn't do multiplication or printing.
To see the desired output, you can add a reset() member function to your class:
class multi{
private:
int a;
int b;
public:
multi(int m, int n) : a(m), b(n) {} //rewrote it
void reset(int m, int n) { a = m; b = n; } //added by me
void multiply(){
cout << "\n\n" << a*b;
reset(5, 5); //<-------------- note this
cout << "\n" << a*b;
}
};
By the way, prefer using member-initialization-list when defining constructors.
When you're calling the constructor multi(5, 5) you're actually creating a temporary object that is immediately destructed.
This doesn't work, because multi(5, 5); creates a temporary object of class multi, which is immediately destroyed, because it is not used for anything
Since multiply() is a member function of class multi, it has access to the private members, so it can just set a and b directly. You can get your expected output by rewriting multiply like this:
void multiply()
{
cout << "\n\n" << a*b;
b = 5;
cout << "\n" << a*b;
}
You can't call constructors like this. What your code does is create a new temporary instance of multi, which gets discarded immediately.
Once an object is constructed, you can't call its constructor again. Create an assign() function or something similar in your class.
You can't call a constructor of an already created object. What you are doing in code is, creating a temporary object.
Compiler will report error if you do try to do
this->multi(5,5).

Dependent variables in C++?

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.