A newbie question regarding variable

when a=5, and how can a also = a+1 ? and which a does the result look for to + b ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 // operating with variables

#include <iostream>
using namespace std;

int main ()
{
  // declaring variables:
  int a, b;
  int result;

  // process:
  a = 5;
  b = 2;
  a = a + 1;
  result = a - b;

  // print out the result:
  cout << result;

  // terminate the program:
  return 0;
}
= is the assignment operator not comparison which is ==.

In your case it takes a adds 1 to it and assigns it back to a. Shorter it would be a++; or ++a; or a += 1. They all express the same.

and which a does the result look for to + b ?
hm, I don't understand? Do you mean if it cares whether result is positive or not? No it doesn't. For this you may use abs():

http://www.cplusplus.com/reference/cstdlib/abs/?kw=abs
a = 5; means, take the value on the right hand side of the = sign and store it in the variable to the left of the =.

a = a + 1; means first calculate the result of whatever is on the right, a + 1 then after doing that, store the result in the variable on the left.

It can be useful to write down the name of each variable as a column heading. Then as each program line is executed, write down the value of each variable.

                     |   a     |    b    | result  |
----------------------------------------------------
  int a, b;          | unknown | unknown |    -    |
  int result;        | unknown | unknown | unknown |
                     |         |         |         | 
  a = 5;             |    5    | unknown | unknown |
  b = 2;             |    5    |    2    | unknown | 
  a = a + 1;         |    6    |    2    | unknown |
  result = a - b;    |    6    |    2    |    4    |
 
if i add a = a + a, would a be equal to 12 ? and does it have different outcomes if i change the order ?

like if i put
1
2
3
a = 5
a = a + a
a = a + 1


would a still be 6 ? or it would be 11 ? since a=5+5, and a=10+1...
"a" would be 11
you cant print out "a" in between
so whatever put to the last of the order will be calculated last right ? like staring from from line one to line three, from higher priority to lower, is that what you mean ?
1
2
3
a = 5
a = a + a
a = a + 1
Yes. Under ordinary circumstances the lines of code are executed in sequence, starting from the top and proceeding line by line.

That is, until you start adding loops, or if-else conditions, but none of those apply here.
Last edited on
Topic archived. No new replies allowed.