Syntax Comparison Basics
This module delves into the fundamental syntax differences between JavaScript and C++, covering variable declarations, control flow, functions, and basic data types.
Variable Declaration and Type System
JavaScript is dynamically typed, meaning variable types are determined at runtime. C++ is statically typed, requiring explicit type declarations at compile time.
Control Flow Statements Comparison
Both languages support common control flow structures like if/else, for, while, and switch, but with minor syntactic differences.
If/Else Statements
For Loops
Function Definition and Calling
Functions in C++ typically require explicit return types and parameter types, but can also use the auto keyword (C++11) for type deduction, or templates to implement generic functions.
Scope and Lifetime
Both languages have block scope, but C++ variables have a more explicit lifetime tied to their scope.
Basic Data Type Comparison
C++ has a richer set of primitive data types with fixed sizes, offering more control over memory.
| JavaScript Type | C++ Equivalent(s) |
|---|---|
number | int, float, double, long, short, etc. |
string | std::string, char[], char* |
boolean | bool |
null | nullptr (C++11), NULL (C-style) |
undefined | No direct equivalent; often represented by nullptr or specific logic |
object | class, struct, union |
symbol | No direct equivalent |
bigint | long long (for larger integers), external libraries for arbitrary precision |
Operators and Expressions
Most arithmetic, comparison, and logical operators are similar, but C++ has additional operators for pointers and memory management.
Module Import and Header File Inclusion
C++ uses the #include preprocessor directive to include header files, similar to JavaScript's import statements. C++ namespaces are used to organize code and prevent naming conflicts.
Practice Questions:
- Explain the difference between static and dynamic typing, providing examples from both JavaScript and C++.
- Write a C++ program that takes a user's age as input and prints whether they are a minor, an adult, or a senior citizen, using
if/else if/elsestatements. - How do namespaces help in C++ programming? Provide a simple example.
Project Idea:
- Create a simple command-line program in C++ that calculates the area of different shapes (circle, rectangle, triangle) based on user input, demonstrating function usage and basic data types.