Keyword and Default Parameters
Keyword Parameters
Keyword Parameters
- One declaration for Ada.Integer_Text_IO.Put is similar to this (but see below):
package Ada.Integer_Text_IO is
...
procedure Put(Item: Num; Width: Field; Base: Number_Base);
Put has three formal parameters:
- Item - the integer to print
- Width - how many spaces to use to print the integer
- Base - the base to print (eg base 2 or base 16)
Parameter passing can be positional - matched by position:
put(i, 1, 2); -- Positional: item i, width 1, base 2
Parameter passing can be by Keyword!
- Matched by parameter name
- Can be in any order
put(i, 1, 2); -- Positional: item i, width 1, base 2
put(Item => i, Width => 1, Base => 2); -- Keyword
put(Width => 1, Base => 2, Item => i); -- Any order
Can mix positional and Keyword
put(i, Width => 1, Base => 2);
put(i, Base => 2, Width => 1);
put(i, 1, Base => 2);
-- put(Width => 1, i); -- Error. What's wrong?
-- put(Width => 1, i, Base => 2); -- Error
-- put(2, Item => i, Width => 1); -- Error
Keyword Parameters - Benefits
- Easier to write (don't have to know order)
- Easier to read (don't have to know order)
- Easier to read (avoid looking up parameters)
- More reliable (can't pass parameters in wrong order)
- More reliable (all of the above)
Default Parameters
Default Parameters
- A more complete declaration for Ada.Integer_Text_IO.Put:
procedure Put(Item : Num;
Width : Field := Default_Width;
Base : Number_Base := Default_Base);
The Width parameter has the default value Default_Width
- If put is called without a width, then the default value is used
- Default_Width is a constant defined in package Ada.Integer_Text_IO.
- What is the default width for an integer? Why?
-- Check the value
put(default_width); -- 11
The Base parameter has the default value Default_Base
- What is the default base?
put(default_base); -- 10
So the following are all the same:
put(i, 11, 10); -- width 11, base 10
put(i, 11); -- width 11, base 10
put(i); -- width 11, base 10
Consider the following:
put(i);
put(i, 1); -- width 1
put(i, 1, 2); -- width 1, base 2
put(Item => i);
put(Item => i, Width => 1);
put(Item => i, Width => 1, Base => 2);
put(Width => 1, Item => i);
put(Width => 1, Base => 2, Item => i);
put(i, Width => 1);
-- put(Width => 1, Base => 2); -- What's wrong?
OLD NOTES ON Keyword, Positional, and Default Parameters
Motivation
- Concern for programmer: easier to read and write
- Reliability: mistakes less likely
Keyword Parameters
Default Parameters
- Parameters can have default values
- Example: for new_line, the default is 1
procedure new_line(Count: Positive := 1) ...
For integer_text_io, the default width is 11 (big enough for 2 billion and a sign)
procedure put(Item: Integer; width: Natural := 11) ...