Operator shorthand


#1

Hi everyone,

Complete n00b and 40something trying to learn something new. When trying to learn the operator shorthand I got the first part to work.

#include <stdio.h>

int main(int argc, const char * argv[])
{
    
    int x=5;
    printf("x is %d\n", x=x+1); //x should now be 6
    return 0;
    
    
}

This does give me the answer of x is 6.

But I (because I am learning all of this by myself) don’t get how to work the next part where:

int x=5;
x++; //x is now 6

Mine keeps coming up with 5.

#include <stdio.h>

int main(int argc, const char * argv[])
{
    
    int x=5;
    printf("x is %d\n", x=x++); //x should now be 6
    return 0;
    
    
}

Also am I supposed to be using spaces where I don’t think I am in certain places.

I know this might not be a big deal, but I am trying to focus on everything one step at a time. It really is all making sense to me, just keeping things together in a notebook and writing as I go along.

Thanks to everyone.

Matt.


#2

OK did some playing around and found that if I wrote it

#include <stdio.h>

int x=5;
printf("x is %d\n", ++x);
return 0;

That this did work. So is there a way that I am missing through the book writing?


#3

You are not alone: I am 5.7 decades something. There is no age limit for learning new things, especially computing. Remember the saying: “Rolling stone gathers no moss.”

Meanings of the pre and post increment operators (++x vs x++):

int w = 0;
int x = ++w;    // w is now 1, and so is x

int y = 0;
int z = y++;    // y is now 1 but z is 0

int x = 0;
if (x++) [engine start];  // won't start

int y = 0;
if (++y) [engine start];  // will start

Thus, we can deduce:
++x := "increment x by 1 then use the resulting value."
x++ := “use the value of x and then increment it by 1.”