Ugrás a tartalomhoz

Szerkesztő:LinguisticMystic/cpp/Variables

A Wikiszótárból, a nyitott szótárból

🔢 Variables in C++

[szerkesztés]

In programming, variables are essential elements that allow us to store and manipulate data. Think of them as labeled boxes in your computer’s memory where values like numbers, characters, and text can be kept and used later.

Understanding how variables work is a fundamental step in mastering programming. Let’s explore how to declare, initialize, and use variables effectively in C++.



📦 Declaring Variables

[szerkesztés]

To declare a variable in C++, you specify its type followed by its name (identifier):

bool ourBoolVariable;   // Boolean (true/false)
int ourIntVariable;     // Integer
float ourFloatVariable; // Floating point
char ourCharVariable;   // Single character

🚫 This is invalid:

void ourVoidVariable; // Error! 'void' means "no type", cannot be used for variables

📝 Naming Rules

[szerkesztés]
  • Must start with a letter or underscore (not a digit)
  • Case-sensitive: value and Value are different
  • Avoid C++ keywords (int, return, class, etc.)
  • Use meaningful names for clarity (e.g., userScore, not us)



📍 Memory and Addresses

[szerkesztés]

A variable represents a memory location. In C++, we can print its address using the address-of operator &:

#include <iostream>
using namespace std;

int main() {
    int ourIntVariable;
    cout << &ourIntVariable << endl; // Output: e.g., 0x7ffcc3f32a8c
    return 0;
}

📌 This tells us where the variable is stored in RAM.



🧮 Assigning Values

[szerkesztés]

After declaring a variable, assign it a value with the assignment operator =:

ourBoolVariable = false;
ourIntVariable = 100500;
ourFloatVariable = 3.14f;
ourCharVariable = 'X';

⚠️ You must assign a value of the correct type. This is invalid:

ourIntVariable = "twenty"; // ❌ Error: wrong type

🧠 Evaluation Logic

[szerkesztés]

The value on the right side of = is evaluated first, then stored into the variable on the left:

int number;
number = 2 + 2 * 2; // evaluates to 6, not 8
number = number + 4; // now contains 10

❗ Uninitialized Variables

[szerkesztés]

If you declare a variable but don’t assign it a value, it contains garbage data:

#include <iostream>
int main() {
    int a;
    std::cout << a; // ⚠️ Undefined behavior
    return 0;
}

⚠️ C++ does not initialize variables to zero by default. Use initialization to avoid bugs.



🛠️ Initialization Techniques

[szerkesztés]

Instead of declaring and assigning in two steps, you can initialize a variable at the same time:

1. Copy Initialization

[szerkesztés]
int x = 10;

2. Direct Initialization

[szerkesztés]
int y(5);

3. Uniform Initialization (C++11+)

[szerkesztés]
int z{7}; // Preferred for most types

✔️ Uniform initialization is versatile and works with built-in types, structs, arrays, and classes.



📃 Multiple Declarations

[szerkesztés]

You can declare and initialize multiple variables of the same type in one line:

int x = 100, y = 66;
int c(12), p(32);
int e{97}, f{150};

This makes your code cleaner when dealing with many variables.



🔒 Constants

[szerkesztés]

To create variables that cannot be changed, use const:

const float pi = 3.1415;
pi = 3.15; // ❌ Error

⚠️ A const must be initialized immediately:

const double grav; // ❌ Error: not initialized

Use constants for values like mathematical constants or configuration parameters.



🧾 Summary

[szerkesztés]
Concept Example Notes
Declaration int age; Reserves memory
Assignment age = 25; Stores value
Initialization int age = 25; Combines both
Multiple Variables int x = 1, y = 2; Cleaner syntax
Constants const int max = 100; Immutable after init
Invalid Types void x; Not allowed



✅ Best Practices

[szerkesztés]
  • Always initialize variables.
  • Choose descriptive names.
  • Prefer uniform initialization {} for safety and clarity.
  • Use const when a variable’s value should not change.



🔚 Final Thoughts

[szerkesztés]

Variables are the backbone of any program. Mastering their declaration, initialization, and usage is your first big step toward writing effective C++ code.

Keep experimenting with different data types, try printing addresses, test uninitialized variables, and see how different initialization methods behave in your compiler. Practice is the key to mastering programming!