answersLogoWhite

0

Sample program in c plus plus with parameter?

Updated: 8/18/2019
User Avatar

Wiki User

9y ago

Best Answer

C++ doesn't have parameters it has arguments, both formal and actual. Actual arguments are the arguments you pass to a function. Formal arguments are the arguments used by the function and which are treated as local variables within the function body. Formal arguments always fall from scope when the function returns. In order for a function to make changes to the actual argument you you can either return the formal argument by value and assign the function to the actual argument upon return, or you can pass the argument by reference. In the former case, the returned value is temporary. If the function is not assigned to the actual argument, the temporary value falls from scope. In the latter case, the actual and formal arguments both refer to the same object through separate names (aliases). Thus any operations performed on the formal argument will affect the actual argument (they are one and the same object).

Example:

// Forward declarations.

int byval (int);

void byref (int&);

int main()

{

int actual = 42;

byval (actual);

// The byval formal argument is no longer in scope.

// Although a temporary value of 84 was returned,

// it wasn't assigned to anything and is no longer

// available.

// The actual argument still has the value 42.

actual = byval (actual);

// The byval formal argument is no longer in scope,

// however, its value was returned and assigned

// to the actual argument.

// The actual argument now has the value 84.

byref (actual);

// The formal argument and the actual argument are

// one and the same argument.

// The actual argument now has the value 42.

}

int byvalue(int formal)

{

formal *= 2;

return formal;

}

// The formal argument no longer exists, but its value

// was pushed into the function's return address. That

// value will cease to exist unless the caller immediately

// assigns the function's return value to a variable.

void byref(int& formal)

{

formal /= 2;

}

// The formal argument no longer exists and nothing

// was pushed onto the function's return address.

// However, formal was just an alias for the actual

// argument, thus the actual argument has already

// been updated.

User Avatar

Wiki User

9y ago
This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: Sample program in c plus plus with parameter?
Write your answer...
Submit
Still have questions?
magnify glass
imp