Syntax, Data Types, and Declarations
- Syntax: the formal rules governing how valid instructions are written in a programming language.
- Semantics: The set of rules that determines the meaning of instructions written in a programming language.
- Identifier: A name associated with a function or data object used to refer to that function or data object.
- main
- variable names.
- constant names.
- Reserved words:
- Words that have special meaning in c++.
- here is a list
- Note c++ is a living/growing language.
- Different versions are know as c++xx
- C++98 was really the first.
- C++03 was a minor change.
- C++11 was a major change.
- C++14, C++17 and C++20 are others
- Syntax rules for identifiers
- Must start with letter or _
- But don't use _, that is reserved for compiler things.
- Can only contain letters, numbers and _
- Can not be a reserved word.
- Conventions for identifiers
- Should have a meaning.
- Variables:
- start with lower case.
- Each new word starts with upper case.
- Functions:
- Start with upper case
- Each new word starts with upper case.
- Constants
- All upper case
- Words have a _ between them.
- Data types
- We need to tell the compiler what type of data we will be storing.
- a reference but perhaps not.
- Basic:
-
int
- Integer: a whole number.
- -2, 0, 130
-
float
- A number in scientific notation.
- 0.34
- 3.4x1022
-
char
- A character.
- inside ''
- 'a', '6', '.'
- We will discuss these further in a bit.
-
string
- Not a built in type.
- Should use
#include <string>
- A collection of 0 or more characters.
- "hello", "", "007"
- Declaring items
- A declaration is a statement that associates an identifier with a data object, function or data type so that the programmer can refer to that item by name.
- EVERYTHING must be declared before it can be used.
- Syntax for declaring a variable
datatype identifier;
datatype identifier = value;
datatype identifier, identifier, ... , identifier;
datatype identifier = value, identifier = value, ... , identifier = value;
-
datatype identifier{value};
- Or any combination.
- The last is the current preferred method.
- In general, it is best to initialize everything when it is declared.
- Declaring a constant
-
const datatype identifier = value;
-
const datatype identifier {value};
-
const datatype identifier = value, identifier = value, ...;
-
const datatype identifier {value}, identifier {value} , ...;
- Constants should be used anytime a value has a name.
-
const int MAX_PEOPLE = 5;
- Silly constants should not be declared however
-
const int FIVE = 5;
-
const FIRST_CONSTANT = 42;