Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
basics
arguments

Arguments in C++ program

Educative Answers Team
svg viewer

Default arguments

When you write a function that takes some arguments as a parameter in C++, you can assign a default value to that argument while declaring it.

Syntax

int SquareThisNum(int num = 0) // This will set default value to 0.
#include <iostream>
using namespace std;

int SquareThisNum(int num = 0){
  return num * num;
}

int main() {
  // No argument is passed so square of 0 is returned.
  cout << SquareThisNum();
  return 0;
}

Pass by reference

In C++, pass by reference (also called pass by address) means, “pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual argument is made in memory,” i.e., the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, then the effect is visible to the caller’s variable.

Syntax

void SquareThisNum(int num, int &result)

Note: The & symbol is used to pass by reference.

#include <iostream>
using namespace std;

void SquareThisNum(int num, int &result){// `result` argument in the callee
  result = num * num;
}
int main() {
  int res = 0;// caller function argument
  cout << res << endl;
  SquareThisNum(5, res);
  cout << res << endl;
}

Pass by value

In C++, pass by value means that a copy of the actual argument’s value is made in the memory, i.e., the caller and callee have two independent variables with the same value. If the callee modifies the parameter value, the effect is not visible to the caller.

#include <iostream>
using namespace std;

void SquareThisNum(int num, int result){// `result` argument in the callee
  result = num * num;
}

int main() {
  int res = 0;// the caller function
  SquareThisNum(5, res);
  cout << res << endl;
}

RELATED TAGS

c++
basics
arguments
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring