예를 들어
int main() {
bool a[50];
cout << a[25] << '\n'; // 0
}
이러면 걍 기본초기화값이 0이잖아, int도 마찬가지고.
컴파일러 마다 다를수있더던데, c++ 은 gcc or clang 2개뿐이고, 코테에서 쓰는것도 clang인데,
왜 0으로 초기화해야만 정답인지 궁금하네.
예를 들어
이러면 걍 기본초기화값이 0이잖아, int도 마찬가지고.
컴파일러 마다 다를수있더던데, c++ 은 gcc or clang 2개뿐이고, 코테에서 쓰는것도 clang인데,
왜 0으로 초기화해야만 정답인지 궁금하네.
키워드: data-segment, bss
In C++, it is not necessary to initialize an array with zeros, but doing so can help prevent issues with uninitialized memory. When you create an array without initializing its elements, the array will contain whatever values are present in the memory allocated for it. These values can be unpredictable and lead to undefined behavior when used in your program. Initializing an array with zeros ensu
Initializing an array with zeros ensures that all elements have a known and consistent starting value. This can help prevent bugs and make your code more predictable and easier to reason about.
In the context of the data-segment and bss (Block Started by Symbol), initializing an array with zeros can have some implications on memory allocation.
Data Segment: The data segment is a part of the virtual memory of a program that contains initialized global and static variables. When you create an array with initialized values (e.g., `int myArray[5] = {1, 2, 3, 4, 5};`), it is stored in the data segment. However, if you initialize all elements with zeros, the compiler may optimize the array to be stored in the bss instead.
BSS (Block Started by Symbol): The bss segment is another part of the virtual memory of a program that contains uninitialized or zero-initialized global and static variables. Storing the zero-initialized arrays in the bss segment has two benefits:
a. Memory efficiency: The bss segment does not take up space in the executable file on disk, which reduces the file size. Instead, the memory for the bss segment is allocated by the operating system when the program is loaded into memory.
b. Faster startup time: When the program is loaded, the operating system can efficiently zero-initialize the entire bss segment in one operation, rather than setting individual values for each variable.
나도 GPT한테 물어봤더니 이러던데, 걍 위에 data segment, bss가 전역변수일때 적용되고, stack에 저장되는 지역변수는 쓰레기값이 들어간데.
https://ideone.com/26XY6M
쳐보면 결과값 1 1 나옴
https://ideone.com/ORG7KN
이렇게 해도 초기화 안하면 1 이 출력되어 버림