-1

error not happen in first code when i define secound variable with default value but first variable not

#include <iostream>
using namespace std;

#include<cmath>

int ahmed(int x, int y = 7);

int main()
{
    ahmed(1, 6);
    return 0;
}

int ahmed(int x, int y)
{
    cout << x << endl;
    cout << y;
}

error happen in secound code when i define firsr variable with default value but secound variable not

#include <iostream>
using namespace std;

#include<cmath>

int ahmed(int x = 7, int y);

int main()
{
    ahmed(1, 6);
    return 0;
}

int ahmed(int x, int y)
{
    cout << x << endl;
    cout << y;
}

The second code is supposed to be correct, so why does the error occur?

#include <iostream>
using namespace std;

#include<cmath>

int ahmed(int x = 2, int y = 7);

int main()
{
    ahmed(1, 6);
    return 0;
}

int ahmed(int x = 2, int y = 7)
{
    cout << x << endl;
    cout << y;
}

in this case third code why error occurs

mch
  • 9,424
  • 2
  • 28
  • 42
  • 5
    It's a basic C++ rule, explained in [the documentation](https://en.cppreference.com/w/cpp/language/default_arguments), various C++ books, and probably also by your compiler error message. – pptaszni Aug 09 '23 at 09:43
  • From the first variable with default value on all succeeding ones must provide one as well. If it wasn't alike you'd end up in a pretty deep chaos, even in your simple example (the failing one) the first function parameter you *provide* would be in one case the first for the function *receives* (if not defaulting the first) or the second one. Having even more parameters would lead to do deep analysis which parameter provided is which one received... – Aconcagua Aug 09 '23 at 09:46
  • 1
    Side note: About [`using namespace std`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)… – and if you still insist on using it, then usually it is applied *after* including headers. – Aconcagua Aug 09 '23 at 09:50
  • Proper formatting and especially indentation makes your code much more readable. Not too much of an issue here, just too simple code, but once it gets more complex it will get a night mare. – Aconcagua Aug 09 '23 at 09:53
  • 1
    That's the way default arguments are specified in C++. If some function arguments are defaulted, and some not, the defaulted ones must be the last ones. There has to be some consistent logic to avoid ambiguity if the calling code explicitly provides some but not all arguments - while other schemes are possible, "defaults at the end" is the scheme chosen – Peter Aug 09 '23 at 10:09
  • The third example breaks the rule that a parameter can only be given a default value once. You are not allowed to give it another value later, not even if it is the same value. – BoP Aug 09 '23 at 10:19

0 Answers0