csjr
csjr

Reputation: 136

C pointer sum "not working"

I do not understand what is the point in the else sentence *nombre=(*nombre)++.

Output shows "fernando" and what i thought it was going to show was "ffsoboep" because of the sum. But it seems that *nombre=(*nombre)+1 is different to *nombre=(*nombre)++;

My question is why is that happening? how does "++" operator works in that case. Thanks.

void recursiva (char * nombre)
{

    if (*nombre != '\0')
    {
        recursiva(nombre+1);
        if(*nombre > 'A' && *nombre < 'Z')
        {
             *nombre=*nombre | 32;
        }
        else
        {
             *nombre=(*nombre)++;
             printf("%c \n",*nombre);
        }
    }
}

int main()
{
    char nombre[]="Fernando";
    recursiva(nombre);
    printf("%s",nombre);
}

Upvotes: 1

Views: 218

Answers (2)

Gari BN
Gari BN

Reputation: 1685

I ran your code and actually got "ffsoboep".

If you see that in other compilers you get "fernando", I believe that the following point is not defined in the standard:

*nombre=(*nombre)++;

This is post increment. The value of (x++) is the value of x before the increment (i.e., x == x++ is true). The question is when does the increment is done.

If the increment is done immediately or after the evaluation of the right side of the = expression, then you first increment the value, and then re-assign the value of the expression (*nombre)++ (which is the value before the increment) to the already incremented *nombre.

If the increment is done, after all the expression is evaluated, then you first assign the (same) value to *nombre, and only then increment.

I think this is not defined in the standard, and therefore - you might see different behaviours. I encountered similar case in the past.

Upvotes: 0

user2357112
user2357112

Reputation: 280251

(*nombre)++

doesn't mean the same thing as

*nombre + 1

It means "return the original value of *nombre, with the side effect of increasing *nombre's value by 1". Note that when exactly the value of *nombre increases is rather vague; while it happens after the value of (*nombre)++ is computed, it might happen before, after, or during the assignment to *nombre, with unpredictable results.

If you want to increase the value of *nombre, you don't need to assign the value of (*nombre)++ back to *nombre, and in fact, trying to do so is undefined behavior. As a first approximation, the program is allowed to do anything, up to and including making demons fly out your nose. Just use ++:

(*nombre)++;

or += 1:

*nombre += 1;

Upvotes: 2

Related Questions