EmbLogic's Blog

assignment no.1 Qno. 12

Dear all
In question no. 12 of assignment Ist
int ten =10;
int two=2;
printf(“%d minus%d=%d\n”,ten);
printf(“%dminus %d=%d\n”,ten,2,ten-two);
printf(“%dminus%d is %d\n”,ten);
return 0;
i was surprised to c the result of 3rd printf statement. Ist and IInd printf statemnt result was OK. but third print statement was unexpected…can anybody tell me the reason???

2 Responses to assignment no.1 Qno. 12

  1. msiddarth says:

    For the first line of output, the first %d represents the int variable ten, the second %d represents the int constant 2, and the third %d represents the value of the int expression ten – two. The second time, however, the program used ten to provide a value for the first %d and used whatever values happened to be lying around in memory for the next two! (The numbers you get could very well be different from those shown here. Not only might the memory contents be different, but different compilers will manage memory locations differently.)

    You might be annoyed that the compiler doesn’t catch such an obvious error. Blame the unusual design of printf(). Most functions take a specific number of arguments, and the compiler can check to see whether you’ve used the correct number. However, printf() can have one, two, three, or more arguments, and that keeps the compiler from using its usual methods for error checking. Remember, check to see that the number of format specifiers you give to printf() matches the number of values to be displayed.

  2. kamran ali says:

    When a function is called in a C program, the process is as follows:
    the arguments are placed on the stack, in reverse order;
    the function is called;
    the function looks at the stack whenever an argument is required;
    the function places the result, if any, on the stack.

    In your cases, the arguments placed on the stack are the value of ten, namely the integer 10, and a pointer to the format string. The function printf finds the pointer and analyses the string. It needs three integer values, which it identifies on the stack. One of these, should be the first, is the valid integer 10 (in 4 bytes, if 32 bit system), the others are the contents of whatever integer sized (i.e. 4bytes wide) locations precede it on the stack, interpreted as integers. These could be anything: fragments of local variables, dynamic or static links, whatever.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>