Machine-translated by Google. Questions are authored in English.
Top

Discussion

Predict the output?

#include <stdio.h> 
int fun(char *str1) 
{ 
  char *str2 = str1; 
  while(*++str1); 
  return (str1-str2); 
} 
  
int main() 
{ 
  char *str = "GeeksQuiz"; 
  printf("%d", fun(str)); 
  return 0; 
} 

 

  • A.10
  • B.9
  • C.8
  • D.Random Number

Answer: B

Correct answer: 9

while(*++str1); pre-increments before testing, so the character at index 0 is never examined and the pointer stops on the terminating null at index 9. The difference str1 - str2 is therefore 9 - which happens to be the length here, but only because the string is non-empty; on an empty string this code would run past the end.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.