C/c doubt
Expert: Zlatko - 7/1/2011
QuestionQUESTION: main()
{
printf("%c","abcdefgh"[4]);
}
output:
e
sir how the above code works?how e comes as out put?
ANSWER: Hello phaneendra
The compiler puts the text "abcdefgh" somewhere in memory, and in the printf line the compiler replaces the text with a pointer to the text. A pointer, can be used like an array. For example if you have array A, then you can get the 5'th element using A[4]. If you have a pointer, lets call it pA, which points to some memory, then you can get the 5'th element in that memory by using pA[4]. Now it should be clear that the printf line is accessing the 5'th element of the memory holding the text "abcdefgh". Why do I say that pA[4] accesses the fifth element, instead of the 4'th? Because, in C, arrays start at 0. pA[0] is the first element, pA[1] is the second element, and so on.
I hope that helps you out.
Best regards
Zlatko
---------- FOLLOW-UP ----------
QUESTION: main()
{
printf(5+"fascimile");
}
output:
mile
sir can you can explain how the above code works.what is +?what is 5?
ANSWER: Hello Phaneendra
This question is similar to your first question. There is some pointer pointing to the text "fascimile". Actually, it is pointing to the 'f' character. The computer is adding 5 to that pointer. The result of the addition is a pointer pointing to the 'm' character. That new pointer is passed to printf. The printf prints characters starting at the pointer it is given, until it comes to the 0 byte which is at the end of all C strings.
Best regards
Zlatko
---------- FOLLOW-UP ----------
QUESTION: void main()
{
int x=10,y=10,z=5,i;
i=x<y<z;
printf("%d",i);
}
out put:
1
how the above code works?how can i get 1 as out put?please explain."
AnswerIt works like this.
x is not less than y, so x<y returns false or 0.
0 is less than z, so 0<z returns true, or 1.
The 1 gets assigned to i.
It might be helpful to rewrite the expression with brackets to see the order of operation. That would be i = (x<y) < z
What would happen if you had i = x < (y<z) ?