1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M2 Variables
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
15Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M2 Variables

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
15Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Variables & Constants

Overview

At its core, a computer program is just an engine that manipulates data. Variables are named memory locations in your RAM where you can store, update, and retrieve this data.

However, in large software engineering projects, data mutation (variables changing unexpectedly) is the number one cause of bugs. C++ strongly encourages the use of 'Constants'—variables that are locked and physically cannot be changed after they are created. C++ provides two levels of constants: const (which guarantees the value won't change after runtime initialization) and constexpr (which forces the compiler to calculate the value during compilation, completely eliminating runtime calculation cost).

Syntax

cpp
// 1. A standard mutable variable
int score = 10;
score = 20; // Allowed!

// 2. A runtime constant
// (Can be assigned dynamically when the program runs, but never changed again)
const double PI = 3.14159;

// 3. A compile-time constant (Modern C++)
// (The math '100 * 5' is done during compilation, saving CPU cycles at runtime)
constexpr int MAX_USERS = 100 * 5;

Common Pitfalls

  • Failing to initialize a const variable. Writing const int x; x = 5; is a fatal compilation error. Constants must be assigned their value at the exact moment they are declared.
  • Using uninitialized variables. If you write int health; cout << health;, C++ will NOT default it to 0. It will print whatever garbage data happened to be left in that RAM sector by the last program that used it.

Interview Questions

Explain the architectural difference between const and constexpr in modern C++.

const signifies that a variable's value cannot be modified after it is initialized, but that initialization can happen dynamically at runtime (e.g., const int input = getUserInput();). constexpr is much stricter; it guarantees that the value is entirely evaluated and hardcoded during compilation, resulting in zero runtime overhead.

What is 'Const Correctness' and why is it heavily scrutinized in C++ interviews?

Const correctness is the discipline of declaring every variable, function parameter, and class method as const unless it strictly needs to be mutated. It prevents accidental bugs, documents intent, and gives the compiler aggressive optimization opportunities.

Real-World Example

Using compile-time constants to avoid 'Magic Numbers' in business logic.

example
cpp
#include <iostream>

int main() {
    // Magic numbers (like 0.08) scattered in code are impossible to maintain.
    // Instead, define them as strict compile-time constants!
    constexpr double TAX_RATE = 0.08;
    double cartTotal = 50.0;
    
    double finalPrice = cartTotal + (cartTotal * TAX_RATE);
    std::cout << "Total: $" << finalPrice << "\n";
    
    return 0;
}

Check Your Knowledge

Test your understanding of Variables & Constants with these quick questions.

Question 1

Which of the following declarations will force the C++ compiler to evaluate the math BEFORE the program even runs?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Variables & Constants

Overview

At its core, a computer program is just an engine that manipulates data. Variables are named memory locations in your RAM where you can store, update, and retrieve this data.

However, in large software engineering projects, data mutation (variables changing unexpectedly) is the number one cause of bugs. C++ strongly encourages the use of 'Constants'—variables that are locked and physically cannot be changed after they are created. C++ provides two levels of constants: const (which guarantees the value won't change after runtime initialization) and constexpr (which forces the compiler to calculate the value during compilation, completely eliminating runtime calculation cost).

Syntax

cpp
// 1. A standard mutable variable
int score = 10;
score = 20; // Allowed!

// 2. A runtime constant
// (Can be assigned dynamically when the program runs, but never changed again)
const double PI = 3.14159;

// 3. A compile-time constant (Modern C++)
// (The math '100 * 5' is done during compilation, saving CPU cycles at runtime)
constexpr int MAX_USERS = 100 * 5;

Common Pitfalls

  • Failing to initialize a const variable. Writing const int x; x = 5; is a fatal compilation error. Constants must be assigned their value at the exact moment they are declared.
  • Using uninitialized variables. If you write int health; cout << health;, C++ will NOT default it to 0. It will print whatever garbage data happened to be left in that RAM sector by the last program that used it.

Interview Questions

Explain the architectural difference between const and constexpr in modern C++.

const signifies that a variable's value cannot be modified after it is initialized, but that initialization can happen dynamically at runtime (e.g., const int input = getUserInput();). constexpr is much stricter; it guarantees that the value is entirely evaluated and hardcoded during compilation, resulting in zero runtime overhead.

What is 'Const Correctness' and why is it heavily scrutinized in C++ interviews?

Const correctness is the discipline of declaring every variable, function parameter, and class method as const unless it strictly needs to be mutated. It prevents accidental bugs, documents intent, and gives the compiler aggressive optimization opportunities.

Real-World Example

Using compile-time constants to avoid 'Magic Numbers' in business logic.

example
cpp
#include <iostream>

int main() {
    // Magic numbers (like 0.08) scattered in code are impossible to maintain.
    // Instead, define them as strict compile-time constants!
    constexpr double TAX_RATE = 0.08;
    double cartTotal = 50.0;
    
    double finalPrice = cartTotal + (cartTotal * TAX_RATE);
    std::cout << "Total: $" << finalPrice << "\n";
    
    return 0;
}

Check Your Knowledge

Test your understanding of Variables & Constants with these quick questions.

Question 1

Which of the following declarations will force the C++ compiler to evaluate the math BEFORE the program even runs?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A