170 views
	int i=0;
char *a = "abcde\0efgh";
while(a[++i]) printf("%d",*++a - 'a');



the output of the above c code segment?

edited | 170 views
1,2,5?

Output :  1 2

char *a

is string constant it will be stored in memory like this.

ASCII  for  '\0' is 0

Tracing

answered by Veteran (20.2k points)
selected
while(a[++i])
printf("%d",*++a - 'a');

Here first the while condition executes i.e a[++i] --> *(a + ++i) --> So here ++ has high precedence than binary '+'. So first i increments which then is added to address pointed by char pointer a and then finally dereferenced.

Now in the printf statement " *++a - 'a' " --> ++ has high precedence then '*' - dereference and then finally binary '-' will execute.

 Value of i a[i++] --> while loop condition *++a , i value *++a - 'a' , a points to 0 a[1] = 'b' b , i = 1 1 [as 98 - 97 ] , a points 'b' 1 a[2] = 'd' c , i = 2 2 [as 99 - 97] , a points 'c' 2 a[3] = '\0'  --> breaks while loop

Hence the code outputs 12.

answered by Loyal (3.5k points)
but a[3] is not \0..a[5] is \0

pls correct me

@Akriti, see in table when value of i = 1 then a points to 'c'. So a[3] is '\0'.

it it that when in *a++ -'a' is performed,then a is pointing to the to next elemnt now and hence in next iteration of while loop,we will add value of 'i' to that address of A.

and in a[++i]..is'nt the precendence of [] is higher then ++ ??so,it should first check value of a[i] and then increment value of i
#include <stdio.h>
int main() {
int x = 1;
int a[2] = {5,6};
printf("%d\n", a[x = x^1]);
printf("%d\n", a[x = x^1]);
}

@akriti

The way you are evaluating what inside the square bracket, is not OK! ..please check the above program. Where  ^ is bitwise xor.

for example 1^1 = 0  ,  4^1 = 5

answr is 5,6

so @debashish,in a[++i]...++i will be done first and then we will read value of a[i]??

@debashish,@gate mission 1-see this

http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm

here it given that ++x has less precedence than []

I am not denying that, but one should also know when to apply precedence.

+1 vote