C++ Tutorial

C++ Variables

A variable has a type, a name, and a value. Declare the type first: int count = 3;

Declare the type first

A variable is a named box in memory. In C++ you state the type before the name. The compiler then knows how much space to reserve and which operations are allowed. This is unlike Python, where a name appears when you assign to it.

Example

#include <iostream>
using namespace std;

int main() {
  int count = 3;
  cout << count << endl;
  return 0;
}

int is the type. count is the name. 3 is the value. The semicolon ends the statement.

Try the examples at /cpp/try. That editor compiles with g++.

Assignment changes the value

After a variable exists, = stores a new value of a compatible type. The old value is gone. You can declare without a value and assign later — but you must assign before you read, or the program has undefined behavior.

Example

#include <iostream>
using namespace std;

int main() {
  int score = 0;
  score = 10;
  score = score + 5;
  cout << score << endl;
  return 0;
}

Do not print a variable you never initialized. Always give a starting value, even if that value is0.

const does not change

Put const before the type when the value must stay fixed. The compiler rejects any later assignment. Use it for names that are really facts: a tax rate, a maximum, a conversion factor.

Example

#include <iostream>
using namespace std;

int main() {
  const int days_in_week = 7;
  int weeks = 3;
  cout << weeks * days_in_week << endl;
  return 0;
}

Writing days_in_week = 8; after that declaration is an error. That is the point ofconst.

Several variables at once

You can list more than one name after a type, separated by commas. Each name can have its own initializer. Keep the list short. Three related integers on one line is fine. A mixed grab bag is harder to read.

Example

int x = 1, y = 2, z = 3;
double width = 4.5, height = 2.0;
cout << x + y + z << endl;
cout << width * height << endl;

Names

Choose names that say what the value is. C++ is case-sensitive: Count is not count. Start with a letter or underscore. Do not use a keyword such as int or return.

GoodPoor
item_count, taxRate, nx1x2, data, temp2 with no context

Type stays put

An int stays an int. You cannot store a whole sentence in it. You cannot later turn the same name into a double by assigning 3.14 and expecting a new type. Pick the type that matches the data, then keep using that name for that kind of value.

Next: reading values from the keyboard into those variables.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

Average speed on a road

Average speed is total distance over total time. A car that covers 150 km in 2.5 h was doing 60 km/h on average. That is not the speedometer at every instant.

Store distance and time in separate names, then divide. One box called result hides which quantity went wrong when the answer looks odd.

v_avg = Δs / Δt

Example

#include <iostream>
using namespace std;

int main() {
  double distance_km = 150.0;
  double time_h = 2.5;
  double speed = distance_km / time_h;
  cout << "v = " << speed << " km/h" << endl;
  return 0;
}

Biology

Resting pulse

Heart rate is reported in beats per minute. Counting for 15 s and multiplying by 4 is the usual shortcut. 18 beats in 15 s is 72 bpm, a normal resting value for many adults.

The name bpm is the unit. A bare 72 in a file could be age, mass, or a mark out of 100.

bpm = beats_in_15s × 4

Exercise, caffeine, and fever all raise the number. Resting rate is measured sitting, after a few minutes still.

Example

#include <iostream>
using namespace std;

int main() {
  int beats_in_15s = 18;
  int bpm = beats_in_15s * 4;
  cout << "resting heart rate = " << bpm << " bpm" << endl;
  return 0;
}

FAQ: C++ Variables

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ variables examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ variables in this C++ C++ lesson (C++ Variables).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.