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

2 Answers

+3 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 (19.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.3k 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 Jan 2017
  1. Debashish Deka

    9008 Points

  2. sudsho

    5326 Points

  3. Habibkhan

    4798 Points

  4. Bikram

    4676 Points

  5. Vijay Thakur

    4496 Points

  6. Arjun

    4244 Points

  7. saurabh rai

    4222 Points

  8. Sushant Gokhale

    3834 Points

  9. santhoshdevulapally

    3808 Points

  10. Kapil

    3752 Points

Monthly Topper: Rs. 500 gift card

19,239 questions
24,127 answers
53,273 comments
20,327 users