int main() { const double pi = 3.14; //OK int i = f(2); //OK. f is forward-declared std::string str; // OK std::string is declared in <string> header C obj; // error! C not yet declared. j = 0; // error! No type specified. auto k = 0; // OK. type inferred as int by compiler. }
int f(int i) { return i + 42; }
namespace N { class C{/*...*/}; }
定義(Definition)
分配Memory。
特性:
定義同時也會進行宣告。
一個變量只能有一次定義。
範例 :
不包含extern的變量。
初始化的變量。
函式主體。
1 2 3 4 5
int i; extern int j = 3; void dosomething() { cout << "hello world" << endl; }
with braces
1 2 3 4
int main() { int a = 20; cout << "The value of variable a is "<< a << endl; }
The code above shows how curly braces can be used to declare various types of variables and assign values to them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int a{20}; cout << "The value of variable a is: "<< a << endl;
string b{"This is a string"}; cout << "The value of variable b is: "<< b << endl;
std::vector<int> c{10, 5}; cout<< "The values of variable c are: " << endl; ```` - Using curly braces to initialize a variable also prevents narrowing. - **Narrowing**, or more precisely narrowing conversion, is the implicit conversion of arithmetic values that includes a loss of accuracy. ```clike int myint(3.14); // output: 3 std::cout << "myint: " << myint << std::endl;