- When I declare any variable, the value are not decided.
how to declare and initilize at the same time?
int a(0);
int b = 1;
int c{2};
int d = {3};
- const
const int a = 3;
int const a = 3;
- fall through
switch(a)
{
case 1: FALL THROUGH:
case 2: FALL THROUGH:
case 3:
std:: cout <<~
}
In the above code, If a is 1, 2, or 3, we hit the same code.(std::cout~~)
1.5.4 const and pointer
- What the pointer points to is const.(*a = 5ができない)
There isconst
to the left of*
.
const int* a = 10;
int const* a = 15;
- The pointer itself is immutable.(a = &bができない)
There is const to the right of*
.
int *const a = 30;
これはダメ we cannot change what the pointer points to.
*ptr = 2でerror
#include <iostream>
int main()
{
int a = 42;
const int* ptr = &a;
*ptr = 2;
std::cout << *ptr << std::endl;
}
これはいい。we change the pointer itself.
#include <iostream>
int main()
{
int a = 42;
int b = 10;
const int* ptr = &a;
ptr = &b;
std::cout << *ptr << std::endl;
}
we cannot assign const variable to not const pointer.
#include <iostream>
int main()
{
const int a = 42;
int b = 10;
int* ptr = &a;
ptr = &b;
std::cout << *ptr << std::endl;
}
1.5.5 null pointer
null pointer is a special address which does not point to any variable.
we can create null pointer by assigning 0 or nllptr.
int *ptr = 0;
ptr = nullptr;
nullptr does not point to anything, so the following code causes segmentation fault.
int main()
{
int* ptr = nullptr;
*ptr = 42; // ヌル参照
std::cout << "ヌル参照のあと" << std::endl;
}
1.5.6 cast
#include <iostream>
int main()
{
char c = 99;
std::cout << static_cast<int>(c) << std::endl;
}
1.6 配列と文字列
int arr[5];
int arr[5] = {1,2,3,4,5};
int arr[] = {1,2,3,4,5};
If array's length is larger than initialized size, the rest is initialized as 0.
int arr[5] = {1,2,3}
→arr is {1,2,3,0,0}
1.6.2 size of array
#include <iostream>
int main()
{
int arr[5] = {};
int size = sizeof(arr);
std::cout << size << std::endl;
}
size is 20 because sizeof() returns the byte.
#include <iostream>
int main()
{
int arr[5] = {};
int size = sizeof(arr);
std::cout << size/sizeof(int) << std::endl;
}
1.6.3 文字列
\0
is null character.
#include <iostream>
int main()
{
std::string string = "hello,\0 nullcharacter";
std::cout << string << std::endl;
}
the output is "hello,".
1.7.2 range based for