GATE CSE
First time here? Checkout the FAQ!
x
+5 votes
209 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 (45.8k points)  
edited by | 209 views
1,2,5?

2 Answers

+5 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.3k 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 Apr 2017
  1. akash.dinkar12

    3826 Points

  2. Divya Bharti

    2796 Points

  3. Deepthi_ts

    2294 Points

  4. rude

    2142 Points

  5. Prashant.

    1900 Points

  6. Tesla!

    1888 Points

  7. Kapil

    1842 Points

  8. Debashish Deka

    1830 Points

  9. Arjun

    1810 Points

  10. Sanjay Sharma

    1712 Points

Monthly Topper: Rs. 500 gift card

22,177 questions
28,200 answers
63,649 comments
24,364 users