0

So, I finally managed to get my Mario working properly. There was, however, one bug that cost me lot of nerves to find and even thought I removed it successfully, I still don't fully understand why did it occur. Without further ado, here is the loop implemented in my mario.c (where the 'n' is the user-gen input):

for (int a = n; a > 0; a--)
{
    int c = a - 1;
    for (; c > 0; c--)
    {
        printf (" ");
    }
    int b = a - 1;
    int d = n - b;
    for (; d > 0; d--)
    {
        printf ("#");
    }
    printf ("  ");
    d = n - b;
    for (; d > 0; d--)
    {
        printf ("#");
    }
    printf ("\n");
}

The thing is, that during my previous attempts instead of

int c = a - 1;

I tried to use the shorter version of

int c = a --;

which kept on breaking down my pyramids in very asymmetrical ways. After listing the values of my integers I eventually found the issue, I still don't however understand why wouldn't the shorter version work in this case. Is this a syntax issue when one just has to type the full formula while defining an integer, or is there another, perhaps more logical solution that I'm just not seeing?

P.s.: My 1st post here and a complete noob in c, so please be gentle.

1 Answer 1

1

Well, let's see if I can explain. Look at this example:

int a = 10;
int b = a--;  // b = 10
int c = --a;  // c = 8

Why is b = 10 and c = 8? You have to understand the difference. When the -- follows the var, as in a--, it means that the statement is executed and then a is decremented. This means that in the second line, a starts out as 10, b is set to the value of a, or 10, and then a is decremented by 1, so a=9.

Now, when the -- precedes the var, it is executed before the statement is executed. In the case of the last line above, a starts out as 9 (from the previous lines). First, a is decremented by 1, so a=8, and then c is set to the value of a, or c=8.

Note something else very important here. For c = a-1; c is set to the value of a-1, but a remains unchanged. However, for c = a--; or c = --a;, both c and a are updated. Say that a=5. In the former, c=5 and a=4. In the latter, c=4 and a=4.

[EDIT: Some more tips]

There's also the simple usage. a++; is a valid line. It simply increments a by itself and stores the result back in a. It would be the same as a = a + 1;. You could also write ++a to increment. They have the same effect of incrementing a, but since nothing else is being done, it doesn't matter which form is used. Same for a--, etc.

There are also shorthand methods as follows:

c += 5;    //adds 5 to c and stores the result back in c
c *= 2.1;  // multiply c by 2.1

You get the idea. You can research other shortcuts on your own. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .