Home > Net >  Local variables are not allowed in default arguments unless used in unevaluated context
Local variables are not allowed in default arguments unless used in unevaluated context

Time:09-17

I just started with C and I came across this line in a book. I don't completely understand as to what it means precisely. Can somebody please explain it simply with an example as to what it is saying.

I found this link, but it's not very clear as to what it is saying

Link: https://en.cppreference.com/w/cpp/language/default_arguments

CodePudding user response:

We can use static variables as default-value for method and/or function's parameter.

And unevaluated can mean not read from, like sizeof myVariable, in which only the size of the variable's type is get (never the actual value).

But even using sizeof myVariable (as default arg), is only okay since ticket 2082 of Core Language Wording Group (aka CWG).

CodePudding user response:

You first need to understand the concept of unevaluated context. Rather than me explaining it, I found brilliant details here and here.

In short:

In other words, the unevaluated operands are the operands of some operators of the language. They are expressions in all respects, but such that they are never evaluated. The reason is because those operators are there just to query the compile-time properties of their operands.

For example, sizeof operator only queries size of datatype and is not evaluated.

Back to answer your original question:

In function declaration, you cannot pass a local variable (say n) as default argument e.g.,

void f() 
{
    int n = 1;
    extern void g(int x = n); // error: local variable cannot be a 
}

however, unevaluated operands (say sizeof) are allowed, for example:

void f() 
{
    int n = 1;
    extern void h(int x = sizeof n); // OK as of CWG 2082
}

Note that n is local variable but, sizeof is unevaluated operand on variable n (and result is going to be 4 bytes on most modern machines).

Hope this helps (p.s: I don't have reputation to comment so am answering it directly)

  • Related