difference between variable-- and variable-1

whats the difference between (variable--) and (variable-1)
take this code for example(it calculates the triangle number of a given number):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int triangle_count(int i);
int main()
{
    int x;
    cout<<"write a number "<<endl;
    cin>>x;

    cout<<triangle_count(x);

    return 0;
}

int triangle_count(int i)
{
    while(i>0)
    return (i+triangle_count(i-1));

    return 0;


}

when i use i-- in the 20th line it doesn't work as it should.But using i-1 does.
So how does these affect this code?Anyone please explain.
Last edited on
i-- changes the value of i after you have used it.

triangle_count(i--) gives you triangle_cout(i), and afterwards the value of i is changed.

triangle_count(i-1) gives you triangle_count(i-1), and i is unchanged.

Here, run this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{

  int i = 7;

  std::cout << "i = " << i << std::endl;
  std::cout << "i-1 = " << i-1 << std::endl;
  std::cout << "i-- = " << i-- << std::endl; // Here, the output value is 7
  std::cout << "i = " << i << std::endl; // And here i is 6
  return 0;
}

i-- will give you the value i and then decrease it by 1.
i-1 will give you the value i-1 and then the value of i will remain the same.

I think what you are looking for is --i which will decrease i by 1 and then return the new value of i.

That being said, there is a major flaw in your function. Whenever we come across the return keyword, we exit the function. Therefore your function is essentially equivalent to this:

1
2
3
4
5
6
7
int triangle_count(int i)
{
    if(i>0)
        return (i+triangle_count(i-1));
    else
        return 0;
}

I have a feeling that this was not intentional.
Last edited on
Topic archived. No new replies allowed.