If you do not explicitly initialize, whether the initial value is automatically entered or the indefinite value is still entered, a summary of the differences depending on the language and declaration location.
Java#
The default value is automatically entered in the instance variable.
public class Sample{
int x; //Instance variables
void show(){
int tmp; //Local variables
System.out.println("x = " + x);
}
}
Variable type | Default value |
---|---|
int , short , byte , long | 0 |
float , double | 0.0 |
char | '\u0000' |
boolean | false |
Object reference | null |
Even in the case of an array, all elements have default values.
Local variables are not automatically initialized. If you do not explicitly initialize it yourself, you will get a compile error.
However, even if it is a local variable, only the ** array is automatically initialized **.
Reference site http://www.booran.com/menu/java/format.html
C/C++#
Global variables are initialized with default values.
#include <stdio.h>
int g_hoge; //Global variables
int main(){
int a; //Local variables
return 0;
}
Variable type | Default value |
---|---|
int , short , long | 0 |
float , double | 0.0 |
char | '\0' |
bool | false |
Object reference | NULL |
Even in the case of an array, all elements have default values.
Local variables are not automatically initialized.
Unlike Java, arrays of local variables are not initialized either.
For variables with static
, even local variables are initialized.
Reference site http://edu.clipper.co.jp/pg-2-33.html
I'm not sure about variables of classes and structures because their behavior changes depending on the declaration location and how to create an instance.
Although it will initialize itself, it is better to explicitly initialize it yourself in programs that others see.
Recommended Posts