Interesting C interview question inspired from GATE exam.
What
is Output of following c snippet?
int main(){
char
*s="Abhas";
printf("%s",s+s[1]-s[3]);
getch();
}
Answer:
bhas
Reason/Solution:
In the above program role of %s is to display the string whose address is
passed as an argument. This is how a standard printf statement works in c
language. Now since we have passed s- s[1]+ s[3] as an argument therefore first
value of this expression is evaluated. Here ‘s’ would refer to address of first
character in string ‘s’. Since we are subtracting s[1] from s[3] characters at
corresponding position (that are ‘a’ and ‘b’) would be subtracted. On subtracting ‘a’ from ‘b’ (ASCII Value) we
get 1 which is added to address of first character in ‘s’ (also referred as
‘s’). Now printf would get address of second character (address of first
character + 1) as argument so it will display the string starting from second
position. Hence output is bhas.
Click here to checkout more subjective C Interview question answers
You can see the related posts for more c interview questions answers.
Click here to checkout more subjective C Interview question answers
You can see the related posts for more c interview questions answers.
No comments:
Post a Comment