GATE CSE
First time here? Checkout the FAQ!
x
+5 votes
185 views
	int i=0;
	char *a = "abcde\0efgh";
	while(a[++i]) printf("%d",*++a - 'a');

 

the output of the above c code segment? 

asked in Programming by Veteran (43.8k points)  
edited by | 185 views
1,2,5?

2 Answers

+4 votes
Best answer

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 by
+3 votes
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.


Top Users Mar 2017
  1. rude

    4758 Points

  2. sh!va

    3014 Points

  3. Rahul Jain25

    2830 Points

  4. Kapil

    2636 Points

  5. Debashish Deka

    2442 Points

  6. 2018

    1514 Points

  7. Vignesh Sekar

    1416 Points

  8. Akriti sood

    1298 Points

  9. Bikram

    1286 Points

  10. Sanjay Sharma

    1076 Points

Monthly Topper: Rs. 500 gift card

21,470 questions
26,801 answers
61,040 comments
23,037 users