-3

For example, can I define a variable "z" in terms of variables I already defined called "x" and "y" (yes I know these are horrible naming conventions but it's an example). Like this:

int x = 0;
int y = 0;
int z = x * y;

Can you do something like that and just go on with your program or will you get error messages?

Rahiz Khan
  • 33
  • 5

3 Answers3

1

You may be interested in lambdas:

int x = 0;
int y = 0;
auto z = [&x, &y](){ return x * y; };

This code does exactly what you are requesting: calling the z() function would always give you the result that is the multiplication of the x and y variables:

int v = z();
assert(v == x * y);

Even if x or y change you would always get their multiplication:

int x = 0;
int y = 0;
auto z = [&x, &y](){ return x * y; };
assert(z() == 0);
x = 1;
y = 2;
assert(z() == 2);
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
  • This is possibly a good point. Many beginners think that writing `int z = x * y;` acts like a spreadsheet, so `z` will always have the value given by multiplying the **current** values of `x` and `y`. This code will do that. – Pete Becker Sep 06 '20 at 15:41
  • @PeteBecker at least I cannot believe that the author asks for an advice how to assign `z = x * y`. – Dmitry Kuzminov Sep 06 '20 at 16:34
  • Thank you for your answer Dmitry! I am a beginner, obviously. In response to Pete Becker's comment, is he saying that if I have code "int z = x * y;" that it will not automatically update the value of z based on how x and y change? – Rahiz Khan Sep 06 '20 at 19:42
  • @RahizKhan yes, that is what he is saying. The initialization/assignment `int z = x * y` is a one-off event, and is never reevaluated. Lambdas is the opposite: is reevaluated every time you call it. I recommend you to update your question because the majority did not understand your intentions. Please clearly indicate if you need a one-off event or the "a la spreadsheat" behavior. – Dmitry Kuzminov Sep 07 '20 at 01:45
  • @DmitryKuzminov thank you for your response. it is very interesting! – Rahiz Khan Sep 08 '20 at 23:46
0

can I define a variable "z" in terms of variables I already defined called "x" and "y"

int z = x * y;

Totally possible to define z that way. Most if not all languages should allow that basic definition. Except, perhaps you have to be careful with overflow issue. If later in your program you may assign x and y to very large value, then z could overflow. It may be better to do:

long long z = x * y;
artm
  • 17,291
  • 6
  • 38
  • 54
0

Yes, you can.

Also,

int x = 1, y = x;
int z=x*y;

y = x; is possible.