+ 1
C++ challenge Qs
Can someone just explain these two to me? The first one, I understand conceptually why the answer is 85, but I still have questions. 1) int a, b, c; a = 2; b = 4; c = b++ *a; cout <<c<<b; I assume that c just takes the value of b before the addition since b++ is b=b+1, but I didn't realize you could change the value of b (b++) in the c= section...? Unless I'm thinking about this wrong. The second one I have no idea how it's 30. It's highly possible I forgot a lesson with this one haha. 2)int foo(int x, int y){ return x+y;} int foo(double x, double y){return x*y;} int main (){cout<<foo(3.8,8.0);} Future ty to:
3 odpowiedzi
+ 3
About the first case, your understanding is correct. <c> is assigned unmodified value of <b>, multiplied by <a>. And in the output line, the post-increment operation had affected (incremented) value of <b>.
About the second case, there are two variants of foo(), one accepts `int`, the other accepts `double`.
So which foo() gets invoked? it depends on the given argument(s) type. As we can see in main(), the call to foo() involves two `double` literals - 3.8 and 8.0 as arguments. So the foo() that accepts `double` will be the one to be invoked.
Notice that, both foo() variants share a common return type - `int`. So the value that is returned to the caller will be casted to `int`
I hope this helps clear something up
+ 1
Ipang thanks for the response. I think you didn't quite answer my first question however. So, even though b++*a was assigned to "c", this still changes the b value(in post) -- I understand that.
But is it just because of the format of b++ or b-- for ex that would allow the b value to be changed although it is a formula to assign a value to c? Because I assume ordinarily, when you assign something to var "c" for example, the operations done to get that value with certain other variables into it should not affect the variables used correct? ex. e+1 *d/2 - g = n should normally not then change/assign new values to e or d variables right? Is it just the nature of the "++/--" that allows you to assign a value to the used var "b++" WITHIN an assignment to a different var ex. "c"?
Does this question make sense? Unless I am just not understanding something correctly.
For the second one, yes as soon as you said the return value was int, I knew I forgot something. Haha! Makes sense ty.
0
milkcereal
doing operations with pre and post incremented variables is allowed. But you will get warnings if you overdo it.
So probably not a good idea.
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
int c = b++ + ++b + a++ + ++a;
cout << c;
return 0;
}