Overview of a C++ Program

 

image-20240419-000604.png

 

The Basics of C++

C++ is a statically-typed, free-form, multi-paradigm, compiled, general-purpose programming language. Here are some basic syntax rules:

  1. Case Sensitivity: C++ is case sensitive, which means Variable and variable are two different identifiers.

  2. Semicolons: In C++, the semicolon is a statement terminator. Each individual statement must end with a semicolon. It indicates the end of one logical expression.

  3. Comments: Single line comments are created using // and multi-line comments are created using /* */.

  4. Identifiers: An identifier is a name used to identify a variable, function, class, module, or any other user-defined item. It must start with a letter or underscore.

  5. Whitespace: Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement ends and the next begins.

  6. Keywords: C++ has a set of reserved words that are part of the syntax. Examples include int, char, float, bool, for, while, if, etc. These cannot be used as identifiers.

  7. Curly Braces: In C++, curly braces {} are used to group statements together into a single compound statement or block.

  8. Data Types: C++ supports several types of data including integers, floating point numbers, characters, and boolean.

  9. Variables: Variables are instances of data types. A variable must be declared with a type before it is used.

  10. Functions: Functions are blocks of code that perform specific tasks. They are defined with a name, return type, and any necessary parameters.

  11. Classes and Objects: In object-oriented programming with C++, classes are user-defined data types that are templates for creating objects. Classes define the properties and behaviors for these objects.

  12. Scope Rules: C++ has specific rules about where variables and functions can be accessed from in the code. This is based on where they were declared and whether they were declared in a class, function, or global scope.

Remember that these are just some of the most basic syntax rules for C++. There are many more rules and specifics depending on what you're doing, especially as you get into more advanced topics like object-oriented programming, exception handling, and template metaprogramming. Understanding these basic rules will, however, give you a solid foundation to start learning C++.


Additional Information

Comments

Typically, comments can be used to identify the authors of the program, give the date when the program is written or modified, give a brief explanation of the program, and explain the meaning of key statements in a program. In the programming examples, for the programs that we write, we will not include the date when the program is written, consistent with the standard convention for writing such books.Comments are for the reader, not for the compiler. So when a compiler compiles a program to check for the syntax errors, it completely ignores comments

Special Symbols

In C++, special symbols are used to perform specific operations and carry out various tasks within a program. These symbols have specific meanings and are essential for writing correct and effective code. Here are some commonly used special symbols in C++:

  1. Arithmetic Operators:

    • Addition: +

    • Subtraction: -

    • Multiplication: *

    • Division: /

    • Modulus (remainder): %

  2. Assignment Operator:

    • Assignment: =

  3. Comparison Operators:

    • Equal to: ==

    • Not equal to: !=

    • Greater than: >

    • Less than: <

    • Greater than or equal to: >=

    • Less than or equal to: <=

  4. Logical Operators:

    • Logical AND: &&

    • Logical OR: ||

    • Logical NOT: !

  5. Increment/Decrement Operators:

    • Increment: ++

    • Decrement: --

  6. Bitwise Operators:

    • Bitwise AND: &

    • Bitwise OR: |

    • Bitwise XOR (exclusive OR): ^

    • Bitwise NOT: ~

    • Left Shift: <<

    • Right Shift: >>

  7. Special Characters:

    • Parentheses: ( and )

    • Curly Braces: { and }

    • Square Brackets: [ and ]

    • Comma: ,

    • Semicolon: ;

    • Colon: :

    • Period (dot): .

    • Double Quotation Mark: "

    • Single Quotation Mark: '

  8. Escape Sequences:

    • Newline: \n

    • Tab: \t

    • Backslash: \\

These special symbols play crucial roles in expressing program logic, performing calculations, making comparisons, and manipulating data. It's important to use them correctly and understand their meanings within the context of C++ programming.

Keywords

In C++, keywords are reserved words that have predefined meanings and cannot be used as identifiers (such as variable names or function names) within a program. These keywords are an integral part of the language syntax and are used to define various elements and control the flow of the program. Here are some common C++ keywords:

  1. Control Flow Keywords:

    • if: Defines a conditional statement.

    • else: Specifies an alternative branch in a conditional statement.

    • switch: Defines a switch statement for multiple branching.

    • case: Specifies a case within a switch statement.

    • default: Specifies the default case in a switch statement.

    • while: Begins a while loop.

    • do: Begins a do-while loop.

    • for: Begins a for loop.

    • break: Terminates the execution of a loop or switch statement.

    • continue: Skips the remaining code in a loop iteration and proceeds to the next iteration.

    • return: Specifies the value to be returned from a function.

  2. Data Type Keywords:

    • int: Specifies an integer data type.

    • float: Specifies a floating-point data type.

    • double: Specifies a double-precision floating-point data type.

    • char: Specifies a character data type.

    • bool: Specifies a Boolean data type.

    • void: Specifies an empty or no return type.

    • const: Specifies that a variable's value cannot be modified.

    • auto: Specifies automatic type deduction.

  3. Class and Object Keywords:

    • class: Defines a class.

    • struct: Defines a structure.

    • public: Specifies public access for class members.

    • private: Specifies private access for class members.

    • protected: Specifies protected access for class members.

    • new: Dynamically allocates memory for an object.

    • delete: Deallocates memory for an object.

  4. Function Keywords:

    • void: Specifies a function with no return type.

    • inline: Specifies inline function expansion.

    • virtual: Specifies virtual function behavior for runtime polymorphism.

    • static: Specifies a static member or local variable.

    • friend: Specifies a function or class as a friend.

    • operator: Specifies an overloaded operator function.

  5. Exception Handling Keywords:

    • try: Begins a block of code in which exceptions can occur.

    • catch: Handles or catches an exception.

    • throw: Throws an exception.

  6. Other Keywords:

    • namespace: Defines a namespace.

    • using: Introduces a name or namespace into the current scope.

    • template: Specifies a template for generic programming.

    • typedef: Defines a type alias.

    • sizeof: Determines the size in bytes of a type or object.

    • this: Refers to the current object.

These are some of the most commonly used C++ keywords. It's important to note that these keywords cannot be used as identifiers for variables, functions, or other user-defined entities within a program.

Identifiers - Variables

In C++, a variable is a named storage location that holds a value of a specific data type. Variables are used to store and manipulate data within a program. Before using a variable, it must be declared with a valid name and an associated data type. Here's the general syntax for declaring a variable in C++:

dataType variableName;

Let's break down the components of a variable declaration:

  • dataType: This specifies the type of data that the variable can hold, such as int, float, char, bool, or a user-defined data type.

  • variableName: This is the chosen name for the variable, following the rules for naming identifiers in C++. It should be meaningful and descriptive.

For example, consider declaring variables of different data types:

int age; // Declaration of an integer variable named 'age' float salary; // Declaration of a floating-point variable named 'salary' char grade; // Declaration of a character variable named 'grade' bool isStudent; // Declaration of a boolean variable named 'isStudent'

After declaring a variable, you can assign a value to it using the assignment operator (=):

age = 25; // Assigning the value 25 to the variable 'age' salary = 2500.50; // Assigning the value 2500.50 to the variable 'salary' grade = 'A'; // Assigning the character 'A' to the variable 'grade' isStudent = true; // Assigning the value 'true' to the variable 'isStudent'

Alternatively, you can declare and initialize a variable in a single statement:

Once a variable is declared and assigned a value, you can use it in expressions, perform operations on it, and update its value as needed throughout the program.

Variables in C++ have a specific scope, which determines their visibility and lifetime within a program. The scope can be local to a block, function, or global to the entire program, depending on where the variable is declared.

Understanding how to declare and use variables is essential in C++ programming, as they play a crucial role in storing and manipulating data within the program's execution.

Illegal   Identifier

Reason

A Correct Identifier

employee Salary

There   can be no space between

employee   and Salary.

employeeSalary

Hello!

The   exclamation mark cannot be used in an identifier.

Hello

one+two

The   symbol + cannot be used in an identifier.

onePlusTwo

2nd

An   identifier cannot begin with a digit.

second

WhiteSpaces

In C++, whitespace refers to the spaces, tabs, and line breaks (also known as newlines) within the source code. Whitespace is generally ignored by the C++ compiler, and its primary purpose is to improve code readability and organization. Here are some key aspects of whitespace in C++:

  1. Separating Tokens:
    Whitespace is used to separate tokens in C++ code. Tokens include keywords, identifiers, operators, literals, and other elements. For example:

  2. Line Breaks (Newlines):
    Line breaks, represented by the newline character (\n), indicate the end of a line in the source code. They are used to break code into logical and readable lines. For example:

  3. Indentation:
    Whitespace, typically in the form of spaces or tabs, is used for indentation to visually represent the structure of code blocks (e.g., functions, loops, conditionals). Consistent indentation enhances code readability. For example:

  4. Multiple Whitespaces:
    In most cases, multiple consecutive whitespace characters (spaces or tabs) are treated as a single whitespace. Therefore, the number of spaces or tabs used for indentation is a matter of coding style and personal preference. Consistency in whitespace usage is crucial within a project or codebase.

  5. Whitespace in Strings:
    Inside string literals (enclosed in double quotation marks), whitespace is preserved and treated as part of the string content. For example:

While the C++ compiler ignores most whitespace, its proper usage is essential for code readability and maintainability. Consistent indentation, appropriate use of line breaks, and clear separation of tokens contribute to well-organized and readable code. Following established coding conventions and guidelines within a project or team helps maintain a consistent and unified approach to whitespace usage in C++ programs.

COSC-1336 / ITSE-1302 Computer Science - Author: Dr. Kevin Roark