GP32 Increase Variable


pea

developer
Joined
Oct 3, 2004
Messages
1,089
Age
45
Location
New Zealand
Website
www.projectitis.com
Hey all,

Have temporary brain-fry problems :)
You know how
length++;
increases value of var 'length' by one?

What is the shorthand to increase the value pointed to by a pointer-to-an-int?
Basically the shorthand for this:

int *length;
*length = (*length)+1;

Because
*length++

Is very dangerous and incorrect (basically, return the value pointed to by length - which is ignored - and then increase the pointer by 1)
 
To increase the int pointed to by length quickly, you could do:

(*length)++;

or treat it as an array, which is safer and more readable:

length[0]++;

Which is also my preferred method.
 
If you're going for shorthanded elegance, this ...
Code:
#include <stdio.h>

void main(void)
{
	int a[5]={1,8,7,3,6},*l=a;

	printf("%d",*l);

	(*l)+=1;

	printf("%d",*l);

	(*l)++;

	printf("%d",*l);

	*l+=1;

	printf("%d",*l);

	*l++;

	printf("%d",*l);
}
gives...
Code:
12348

Use anything but *l++ ;)
 
gp32rich posted on Aug 18 2005 at 10:25 AM said:
...

Use anything but *l++ ;)

Don't forget
Code:
 ++*l;
as a valid choice :p

Janniz
 
Last edited by a moderator:
Thanks all. Brackets huh :)

Janniz

++*l;

is NOT a valid choice! It would increase the pointer and then return the value. You may be thinking of

++(*l);

:p
 
Squidge posted on Aug 18 2005 at 08:20 AM said:
To increase the int pointed to by length quickly, you could do:

(*length)++;

or treat it as an array, which is safer and more readable:

length[0]++;

Which is also my preferred method.
and mine, this way is much more clear to me (i'm too lazy to comment everything)
 
Last edited by a moderator:
pea posted on Aug 18 2005 at 11:55 PM said:
++*l;

is NOT a valid choice! It would increase the pointer and then return the value. You may be thinking of

++(*l);

:p

I don't have K&R with me now :p but I'm pretty sure that ++*l would do the job...

Pointer dereference and ++ have are both unary operator... so they will have the same priority and will be evaluated from right to left...
++*l is the same as ++(*l) and WRONG *l++ is the same as *(l++)...

I compiled&run this piece of code on gcc 3.3.3 under cygwin:
Code:
#include <stdio.h>

void main(void)
{
int a[5]={1,8,7,3,6},*l=a;

printf("%d",*l);

(*l)+=1;

printf("%d",*l);

(*l)++;

printf("%d",*l);

*l+=1;

printf("%d",*l);

++*l;

printf("%d",*l);

*l++;

printf("%d",*l);
}

and the output was:
123458

See ya
Janniz
 
Last edited by a moderator:
janniz posted on Aug 18 2005 at 01:18 PM said:
Don't forget
Code:
 ++*l;
as a valid choice :p
Hmm. Yeah. I forget about prefixing the increment.
But then again, I hardly ever* use it.



My preferred method of non-inline increment (ie. standalone statement) is v+=1;
v++; on it's own looks kinda nasty to me :p




* never say never :D
 
Last edited by a moderator:
Back
Top