Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function definition with initialized arguments and Function call with less arguments

I came across with a confusing question during an examination. Please help me to understand this concept. Code snippet is including here :

void xyz(int a = 0, int b, int c = 0)
{
    cout << a << b << c;
}

Now the question is which of the following calls are illegal?

(Assume h and g are declared as integers)

(a) xyz();    (b) xyz(h,h);

(c) xyz(h);    (d) xyz(g,g);

Codes:

(1) (a) and (c) are correct (2) (b) and (d) are correct

(3) (a) and (b) are correct (4) (b) and (c) are correct

I tried to compile the code in C++ and I got this error:

error:expected ';',',' or ')' before '=' token
void xyz (int a = 0, int b = 0, int c = 0)

Help me understand the concept.

like image 550
runner Avatar asked Jul 22 '26 04:07

runner


2 Answers

According to cppreference:

In a function declaration, after a parameter with a default argument, all subsequent parameters must :

  • have a default argument supplied in this or a previous declaration; or
  • be a function parameter pack.

Means

void xyz(int a = 0, int b, int c = 0) // Not valid
{
   //your code
}

It is give an error because a has default value, but b after it doesn't have default value. The ordered of function declarations with default argument must be from right to left.

So, use

void xyz(int a = 0, int b=0, int c = 0) // Not valid
{
   //your code
}

Let's see some c++ example:

case 1: Valid, trailing defaults

void xyz(int a, int b = 2, int c = 3)
{
   //your code
}

case 2: Invalid, leading defaults

void xyz(int a = 1, int b = 2, int c)
{
      //Your code
}

case 3: Invalid, default in middle

void xyz(int a, int b = 3, int c);  
{
      //Your code
}
like image 124
msc Avatar answered Jul 23 '26 19:07

msc


Put default assignment in right.

void xyz(int a , int b= 0, int c = 0)
{
    count <<a<<b<<c;
} 

call it like this:

xyz(2,3); 
xyz(2,3,5);
like image 40
Farhad Avatar answered Jul 23 '26 17:07

Farhad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!