PDA

View Full Version : Is this valid C syntax?


singularity2006
03-25-2004, 05:33 AM
I'm doing a short homework assignment for my C class but this loop looks VERY WEIRD! Is it a valid loop?

given:


i=0;
while(i<4 && array[i] != 99)
{
array[i]++;
i++;
}


What the heck is "array[i]++;?" I have never seen anything that looks like that!

cod3gen
03-25-2004, 06:31 AM
The syntax is valid (I suppose you have declared 'i' and 'array' somewhere). But how it will work is another question. Anyway, what array[i]++ does is that it takes the value that is stored in your 'array' variable with the offset 'i' and increment it by 1.

playmesumch00ns
03-25-2004, 07:48 AM
Well it is valid, but it's ugly.
array[i]++;
would just increment whatever is the i'th element of array.

The loop will increment the first four elements of array but will break if one of them is 99.

you've seen something that looks like array[i]++ in the line below it (...in case you haven't, '++' is called the post-increment operator, and just adds one to the expression immediately before it). What matters is the order of evaluation of expressions. The array operator, '[]', has a higher priority than the post-increment operator and so is evaluated first, referencing the ith value of the array. Then the post-increment adds one to it.

This is equivalent to the following:
a = array[i];
a = a + 1;
array[i] = a;



Without seeing the code in context it's hard to know what exactly it is that it's trying to do.

schmu_20mol
03-25-2004, 07:58 AM
Originally posted by playmesumch00ns

Without seeing the code in context it's hard to know what exactly it is that it's trying to do.

looks like some of the little snippets you get to look at while studying... normally you just have to tell if it is valid or not?

playmesumch00ns
03-25-2004, 08:35 AM
I guess the easiest way to check if it's valid or not is just to compile it and see what happens!

Hugh
03-25-2004, 10:52 AM
All that code does is add 1 to each of the first four values of the array.


If you want to get even more confused by code that does the same thing, take a look at this:


for(i = 0; i < 4 && array[i] != 99; array[i]++, i++);

playmesumch00ns
03-25-2004, 12:45 PM
could you also do


for ( i = 0; i < 4 && array[i] != 99; array[i++]++ );

Hugh
03-25-2004, 01:09 PM
Originally posted by playmesumch00ns
could you also do


for ( i = 0; i < 4 && array[i] != 99; array[i++]++ );


You could indeed....

Another option is:

for ( i = 0; ++i < 4 && ++array[i] != 99; );

singularity2006
03-25-2004, 06:14 PM
AH! THANK YOU! I kept thinking of it incrementing the index of the array! Man o man, totally forgot to look at the precedence table to see that it incremented the element of that array index! thanks folks. :scream:

CGTalk Moderation
01-17-2006, 08:00 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.