Three short questions C-ers

• 01-27-2013
Aitra
Three short questions C-ers
Hi guys

I have three separate, non-related code that each give out a certain value that I can't just figure why....

could you help me with them?

Code:

int arr[] = {5,6,7,8,9,10};

int x = 1;

int *p = arr + 2 ; //I have mainly problem with definition of this line

p--;

x = p[x]

this one gives you 7.

the other is a segment : it's to give you 15...why???

Code:

for( i= 3; i != 15; i= i + 2);

and the last gives you just zero. I'm not sure if I totally understand the while(0) loop?

Code:

int main(void) {

int r = -1 ;

while (r++) {

printf("r = %d \n", r);

}
return 0;

}

I'd be grateful for any help
• 01-27-2013
c99tutorial
Rewrite each one in a way that makes sense to you.

1.
Code:

int arr[] = {5,6,7,8,9,10};
int x = 1;
int *p = &arr[2];  // p points to the 7
p--;              // p points to the 6
x = p[x]          // p[1] points to the element one spot after the 6

So x is 7, like you would expect. Notice &arr[2] is the same as arr + 2

2. A general for loop... for(INIT; COND; INCR) STAT; can be rewritten as
Code:

INIT;
while (COND) {
STAT;
INCR;
}

So, using this transformation, your for loop is the same as
Code:

i = 3;
while (i != 15)
i = i + 2;

So the final value is 15. It says in English "Start the loop at i=3. Loop until i becomes 15, then stop. Each time through the loop, increment i by 2"

3. An expression like VAR++ is the same as saying this:
VAR;
VAR = VAR + 1;
So rewrite your third snippet like this
Code:

int r = -1 ;

while (r) {
r = r + 1;
printf("r = %d \n", r);

}
r = r + 1;

• 01-27-2013
Aitra
wow!! thanks a lot!! now I see them all. Very helpful