C++ Comments and Variables
Comments in C++
Comments are ignored by the compiler. They document your code for other developers (and your future self). C++ supports two types:
//— single-line comment: everything after//on that line is ignored./* ... */— multi-line comment: everything between the delimiters is ignored.
#include <iostream>
using namespace std;
/*
* Multi-line comment
* This program demonstrates comments in C++.
* The compiler ignores all comment text.
*/
int main() {
// Single-line comment: print a message
cout << "Hello, C++!" << endl;
int x = 42; // inline comment: x holds the answer
/* You can also use multi-line comments inline */
cout << "x = " << x << endl;
return 0; // 0 = success
}
Variables in C++
A variable is a named storage location in memory. In C++, every variable has a type (determines size and what values it can hold), a name, and a value.
Syntax: type name = value;
| Type | Size | Example | Description |
|---|---|---|---|
int | 4 bytes | int age = 25; | Whole numbers |
double | 8 bytes | double pi = 3.14; | Floating-point numbers |
float | 4 bytes | float temp = 36.6f; | Single-precision float |
char | 1 byte | char grade = 'A'; | Single character |
bool | 1 byte | bool active = true; | true or false |
string | varies | string name = "Alice"; | Text (requires <string>) |
#include <iostream>
#include <string>
using namespace std;
int main() {
// Declaration and initialization
int age = 25;
double salary = 55000.50;
float temp = 36.6f; // 'f' suffix for float literal
char grade = 'A';
bool active = true;
string name = "Alice";
// C++11: auto — compiler deduces the type
auto count = 10; // int
auto price = 9.99; // double
auto letter = 'Z'; // char
// Multiple declarations on one line (same type)
int x = 1, y = 2, z = 3;
// Uninitialized local variable — UNDEFINED BEHAVIOUR, avoid!
// int bad; // contains garbage value
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Salary: " << salary << endl;
cout << "Grade: " << grade << endl;
cout << "Active: " << boolalpha << active << endl;
cout << "x+y+z: " << x+y+z << endl;
return 0;
}
Constants
Use const or constexpr to declare values that cannot change after initialization. constexpr (C++11) is evaluated at compile time — prefer it for numeric constants.
#include <iostream>
using namespace std;
int main() {
const double PI = 3.14159265358979;
constexpr int MAX_SIZE = 100; // compile-time constant
// PI = 3.0; // ERROR: cannot assign to const variable
double radius = 5.0;
double area = PI * radius * radius;
cout << "Area of circle: " << area << endl;
// #define (old C-style, avoid in C++)
// #define GRAVITY 9.8 // no type safety, no scope
// Prefer const/constexpr over #define in C++
constexpr double GRAVITY = 9.8;
cout << "Gravity: " << GRAVITY << " m/s²" << endl;
return 0;
}