Sunday 6 July 2014

Functions (Part2)

Functions (C-FAQ's)



Q1: What is the output of the following code?

            int iReverse(int iNum)

            {

                        if( iNum == 0)

                                    return 0;

                        else

                                    printf("%d ", iNum);

                        iReverse(iNum--);

            }

            int main()

            {

                        int iNum=6;

                        iReverse(iNum);

                        return 0;

            }

 

            A.        6 5 4 3 2 1

            B.        1 2 3 4 5 6

            C.        6 5 4 3 2 1 0

            D.        6 till stack over flow

 

           


            Output:        
                        D. 6 till stack over flow
                         iReverse(iNum--) will not make any change in the value of iNum because we are using a post decrement operator here.          


Q2: What is the output of the following code?

            int iModify(int iNum1, int iNum2)

            {

                        int x,y;

                        x= iNum1 * iNum2;

                        y=iNum1 + iNum2;

                        return (x,y);                       

            }

            int main()

            {

                        int iA=5, iB=10;

                        iA=iModify(iA,iB);

                        printf("iA=%d\n",iA);

                        return 0;

            }

 

            A.        iA=5

            B.        iA=10

            C.        iA=50

            D.        iA=15

 

         


            Output:        
      iA=15

                       

Q3: What is the output of the following code?


            void display (char **ptr)

            {

                        char *msg;

                        msg=(ptr += 4)[-2];

                        printf("%s\n",msg);

            }

            int main()

            {

                   char *msg[]={"Hi","Hello","world","function"};

                        display(msg);

                        return 0;

            }

 

            A.        function

            B.        world

            C.        Hello

            D.        Hi

               

         


            Output:
               world

            Explanation:

                        msg is an array of strings.
HI
Hello
World
Function





msg
msg+1
msg+2
msg+3
msg+4




            In display(), initially value of ptr is base address of msg.
                        ptr=msg;
            Then after expression ptr += 4, ptr is pointing to the address msg+4.
            Now ptr[-2] will get execute. Its means *(ptr - 2). Now ptr will move back two positions.
                        msg = *(msg+4 -2 );
                        msg = *(msg+2);
                        msg  =  "World";





<< PREV               [C FAQ's]            NEXT >>

No comments:

Post a Comment