Question:

C programming homework

by Guest60993  |  earlier

0 LIKES UnLike

Hi, I need help with my exercise for C OOP class. Please help thanks!!!

The following program displays 19 as its output. Please explain why?

#include <iostream>

using namespace std;

int main()

{

int &mysub(int &);

int k = 4;

mysub(k) = 19;

cout << k << endl;

int * mysub(int *);

// *(mysub(&k)) = 29; // StatementX

// cout << k << endl; // StatementY

return 0;

} // main

int &mysub(int &ref)

{

ref = 8;

return ref;

} // mysub

ALSO: Please complete mysub(int *) to make StatementX and StatementY work. The output displayed by StatementY will be 29.

 Tags:

   Report

1 ANSWERS


  1. The mysub-function returns the very reference it gets as a parameter. Calling mysub(k) passes a reference to k to mysub, which mysub returns. Thus, doing mysub(k) = 19 is to assign 19 to the return value of mysub(k), which is a reference to k. And via this reference k gets the value 19. The prior assignments of 4 and 8 are overwritten.

    The second mysub will return its parameter too, but this time it is a pointer. It will be called whit &amp;k as parameter, e. g. a pointer to k. That pointer will be returned as it is. The main program then accesses the pointer to store 29 at its target. Here is the function:

    int *mysub(int *ptr) {

    return ptr;

    }

    Instead of StatementX, *(mysub(&amp;k)) = 29; the main program could have done it in steps:

    int *pointerToK = &amp;k;

    int *copyOfPointerToK =mysub(pointerToK);

    *copyOfPointerToK = 29;

    // k now has the value 29  

You're reading: C programming homework

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.