runner
runner

Reputation: 601

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.

Upvotes: 3

Views: 2605

Answers (3)

msc
msc

Reputation: 34588

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
}

Upvotes: 10

Farhad
Farhad

Reputation: 4181

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);

Upvotes: 2

distant1219
distant1219

Reputation: 96

I think it's wrong definition of the function.

void xyz(int b, int a = 0,  int c = 0)

or

void xyz(int a = 0, int b = 0,  int c = 0)

could be ok.

Upvotes: 1

Related Questions