Variables and Constants

2016-12-04  本文已影响15人  某右衛門

LT2 Variables (and Constants)

C++ Syntax

Compiler detects any violation of syntax
Compiler collects the characters of code into Tokens, which are separated by space

Tokens
  1. Keywords: return, namespace, include, int

    • Keywords are reserved
    1. Types: int, bool, string, char, long, short, signed, unsigned, void
    2. Flow Control: if, else, while, do, switch, case, break, continue, default
    3. Others: using, namespace, true, false, new, public
  2. Identifiers: user-defined variables, objects, function names

    • The unique name of objects, variables, functions for identification
    • Keywords cannot be identifiers
    • letters, digits (no leftmost), underscores _, No Hyphen -
      • Hyphen in C++ means Minus (-) Operator
  3. String & Number constants: aka Literals in python

  4. Operators: + - * / << >>, etc

  5. Punctuators: ; , { } ( )

Variables and Constants

Type, Name, Scope of Variables
  1. Type: either predefined or user-defined
  2. Name: the identifier
  3. Scope: the extent to which the variable can be accessed

C++ Predefined Data Types

  1. Numerical: int, double, signed, unsigned, long, short
  2. Character: char
  3. Logical: bool
  4. Other: void

Type Conversion

  1. Implicit Type Conversion
    • Lower ranked are promoted to be higher ranked type: double > int > char
    • Assignment statement will assign the left to match the left type
  2. Explicit Type Conversion
    int a = 1.9; // a = 1;

Constants

Also defined type, name, scope

However constants can not be changed once defined
const type_name constant_name = value

Variable Scope - Local and Global

Scope defines the accessibility boundary of a variable

Conflict of Local and Global Variables with Same Names

The Local Variable hides the Global Variable within its scope
also applies to local local variables wrt local variables

Scope and namespace

A scope can be defined in many ways, eg by

Namespace is used to Explicitly define the scope.
Scope Operator :: is used to identify same-name variables within different scopes

上一篇 下一篇

猜你喜欢

热点阅读