Output of C Program | Set 27
Predict the output of following C programs.
In the above example, we have created an array of 5 elements, whose elements are power of ten (i.e. 1, 10, 100, 1000 and 10,000) and we are printing these element by using a simple for loop. So we are expecting output of above program is ” 1 10 100 1000 and 10000″, but above program doesn’t show this output, instead it shows
"1 8 64 512 10000"
Let us discuss above program in more detail. Inside array we declared elements which starts with “0”, and this is octal representation of decimal number (See this GFact for details).
That’s why all these numbers are in octal representation. “010” is octal representation of decimal “8”, “0100” is octal representation of decimal “64” and so on.
Last element “10000” which doesn’t start with “0”, that’s why it is in decimal format and it is printed as it is.
At first sight, it looks like that the above program will give compilation error, but it will work fine (but will give compilation warning). Observe the above program carefully, in this program “http:” will be treated as goto label and two forward slashes will act as single line comment. That’s why program will work work correctly.
In above program, “ARRAY_SIZE” macro substitutes the expression to get the total number of elements present in array, and we are printing these element by using a for loop. But program doesn’t print anything. Let us see what is wrong with code.
Value returned by the substituted expression is in “unsigned int” format, and inside for loop we are comparing unsigned 5 with signed -1. In this comparison -1 is promoted to unsigned integer. -1 in unsigned format is represented as all it’s bit are set to 1 (i.e. 0xffffffff), which is too big number
After substituting value of macro, for loop look like this.
for (i = -1; 0xffffffff < 5; ++i)
In above loop indeed 0xffffffff is not less than 5, that's why for loop condition fails, and program exits from loop without printing anything.
This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...