-3

I saw a code in which an int variable was declared in a function like

int func(vector<int> a, int lum=0) {...}

I am looking for a idea or logic where anyone can use it..Cause it feels weird. Also tell me if it's right way to code or it was totally foolish of coder?c

shivam13juna
  • 329
  • 4
  • 11

1 Answers1

3

This is called a "default argument". That is, if the user doesn't pass a second value to func, the function will receive 0

For example:

int func(std::vector<int> a, int lum=0)
{
   std::cout << "Received lum value: " << lum << std::endl;
}

int main(){
   std::vector<int> a = {1, 2, 3};
   func(a); // "Received lum value: 0"
   func(a, 2); // "Received lum value: 2"
}

cppreference has a good page on this.

All default arguments must appear last in a function's declaration, and should not appear again in a function's definition if you choose to separate declaration and definition:

int func(std::vector<int> a, int lum=0); // declaration

// ...

int func(std::vector<int> a, int lum){ // definition, no default arguments
   //...
}
AndyG
  • 39,700
  • 8
  • 109
  • 143
  • I couldn't find a duplicate on StackOverflow, and I couldn't find a criteria in "How to Ask" or "How to Answer" to disqualify this question. Also, if you didn't know what it was, it's really hard to Google! If you can find a dup, I'll gladly delete my answer and vote to close as duplicate. – AndyG Jun 16 '17 at 18:09
  • Do not delete your answer please, it is still good even if question is dup – Slava Jun 16 '17 at 18:16
  • @Slava: Ah I see there was a dup after all. Thank you. I've checked the answer there, and it is perhaps incomplete. Perhaps I should migrate this answer to that question thread and delete this one? – AndyG Jun 16 '17 at 18:18
  • I would not bather on your place – Slava Jun 16 '17 at 18:22