Default variable value
A declared variable can be Zero Initialized, Value Initialized or Default Initialized.
The C++03 Standard 8.5/5 aptly defines each:
To zero-initialize an object of type T means:
— if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
— if T is a non-union class type, each nonstatic data member and each base-class subobject
is zero-initialized;
— if T is a union type, the object’s first named data member is zero-initialized;
— if T is an array type, each element is zero-initialized;
— if T is a reference type, no initialization is performed.
To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the
initialization is ill-formed if T has no accessible default constructor);
— if T is an array type, each element is default-initialized;
— otherwise, the object is zero-initialized.
To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default
constructor for T is called (and the initialization is ill-formed if T has no accessible
default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static
data member and base-class component of T is value-initialized;
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized
For example:
#include<iostream>
using namespace std;
static int a; //Zero Initialized
int b; //Zero Initialized
int main()
{
int i; //Undefined Behavior, Might be Initialized to anything
static int j; //Zero Initialized
cout<<"\nLocal Uninitialized int variable [i]"<<i<<"\n";
cout<<"\nLocal Uninitialized Static int variable [j]"<<j<<"\n";
cout<<"\nGlobal Uninitialized Static int variable [a]"<<a<<"\n";
cout<<"\nGlobal Uninitialized int variable [b]"<<b<<"\n";
return 0;
}
You will notice The results for variable i
will be different on different compilers. Such local uninitialized variables SHOULD NEVER be used. In fact, if you turn on strict compiler warnings, the compiler shall report an error about it. Here's how codepad reports it an error.
cc1plus: warnings being treated as errors
In function 'int main()':
Line 11: warning: 'i' is used uninitialized in this function
Edit: As rightfully pointed out by @Kirill V. Lyadvinsky in the comments, SHOULD NEVER is a rather very strong word, and there can be perfectly valid code which might use uninitialized variables as he points out an example in his comment. So, I should probably say:
You should never be using uninitialized variables unless you know exactly what you are doing.
How to set default value for variable?
In the exact scenario you present, you can use default values for arguments, as other answers show.
Generically, you can use the or
keyword in Python pretty similarly to the way you use ||
in JavaScript; if someone passes a falsey value (such as a null string or None
) you can replace it with a default value like this:
string = string or "defaultValue"
This can be useful when your value comes from a file or user input:
string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"
Or when you want to use an empty container for a default value, which is problematic in regular Python (see this SO question):
def calc(startval, sequence=None):
sequence = sequence or []
Assigning default values to shell variables with a single command in bash
Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this.
To get the assigned value, or default
if it's missing:
FOO="${VARIABLE:-default}" # If variable not set or null, use default.
# If VARIABLE was unset or null, it still is after this (no assignment done).
Or to assign default
to VARIABLE
at the same time:
FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.
Show the default value for a variable
From the manual:
To set a global system variable value to the compiled-in MySQL default
value [...] set the variable to the valueDEFAULT
.
That means you can do this:
SET @@GLOBAL.max_connections = 1234;
/*
* Proceed in this order
* 1) Backup current value
* 2) Reset to default
* 3) Read the current value
* 4) Restore the backup value if necesssary
*/
SET @oldvalue = @@GLOBAL.max_connections;
SET @@GLOBAL.max_connections = DEFAULT;
SET @defvalue = @@GLOBAL.max_connections;
SET @@GLOBAL.max_connections = @oldvalue;
SELECT @@GLOBAL.max_connections AS `current value`
, @defvalue AS `default value`
-- 1234 and 151
The @oldvalue
and @defvalue
are user variables.
Python shortcut for variable default value to be another variable value if it is None
The usual idiom is:
def set_data(obj=None, name='delp', type=None):
if type is None:
type = name
(But don't actually use type
as a variable name, it'll mask the built in function as described here: Is it safe to use the python word "type" in my code?)
Easy way to set default values for variables in bash
You can have two files:
- a file containing the default value of variables.
- the client file
Source the default file and then the one from the client. This way, customer's values will be overwritten.
Test
Let's have these two files:
$ cat default
export var1="foo"
export var2="bar"
export var3="bee"
$ cat customer
export var2="yeah!"
Now, let's source them:
$ source default
$ env | grep "^var"
var1=foo
var3=bee
var2=bar
Then let's get customer
's file:
$ source customer
$ env | grep "^var"
var1=foo
var3=bee
var2=yeah!
As you see, variable $var2
has not the value from customer
's file, whereas the others have the value sest in default
.
Setting a default variable value in a function
There's really no shorter clean way than
var int = arg || 400;
In fact, the correct way would be longer, if you want to allow arg to be passed as 0
, false
or ""
:
var int = arg===undefined ? 400 : arg;
A slight and frequent improvement is to not declare a new variable but use the original one:
if (arg===undefined) arg=400;
Related Topics
How to Implement Big Int in C++
How to Iterate Over Cin Line by Line in C++
C++ Templates That Accept Only Certain Types
When I Change a Parameter Inside a Function, Does It Change For the Caller, Too
Can You Use 2 or More or Conditions in an If Statement
Get Human Readable Ast from C++ Code
Rotating a Point About Another Point (2D)
How to Determine the Version of the C++ Standard Used by the Compiler
Changing the Delimiter For Cin (C++)
Difference Between Char A[] = String; and Char *P = String;
Why Can't the Template Argument Be Deduced When It Is Used as Template Parameter to Another Template
Which, If Any, C++ Compilers Do Tail-Recursion Optimization
How to Detect Reliably MAC Os X, Ios, Linux, Windows in C Preprocessor
What Happens When I Print an Uninitialized Variable in C++
Are the Days of Passing Const Std::String & as a Parameter Over