Good Names and Constants

Naming rules

C++ is strict about names. A variable name:

  • can use letters, digits and the underscore _,
  • cannot start with a digit (2cats is not allowed, cats2 is fine),
  • cannot contain spaces or symbols like - or !,
  • cannot be a C++ keyword such as int, return or class,
  • is case-sensitive: score and Score are two different variables.

Good habits

Choose names that say what the value means. Compare:

#include <iostream>
using namespace std;

int main() {
    int x = 60;          // what is x? nobody knows
    int y = 3;

    int minutesPerHour = 60;   // much clearer!
    int hours = 3;
    cout << x * y << " " << minutesPerHour * hours << "\n";
    return 0;
}

Output

180 180

Two popular styles for names made of several words:

  • camelCase: totalPrice, studentName
  • snake_case: total_price, student_name

Tip: Pick one style and stick with it. This course uses camelCase.

Constants: values that never change

Some values should never change, like the number of days in a week. Put const in front, and C++ will refuse to let anyone change it:

#include <iostream>
using namespace std;

int main() {
    const int DAYS_IN_WEEK = 7;
    const double PI = 3.14159;
    cout << "Weeks in 28 days: " << 28 / DAYS_IN_WEEK << "\n";
    cout << "PI is about " << PI << "\n";
    return 0;
}

Output

Weeks in 28 days: 4
PI is about 3.14159

If you try to change a constant, the program won't even compile:

#include <iostream>
using namespace std;

int main() {
    const int DAYS_IN_WEEK = 7;
    DAYS_IN_WEEK = 8;
    return 0;
}

Output (the program does not compile)

main.cpp:6:18: error: cannot assign to variable 'DAYS_IN_WEEK' with
      const-qualified type 'const int'
    DAYS_IN_WEEK = 8;
    ~~~~~~~~~~~~ ^
main.cpp:5:15: note: variable 'DAYS_IN_WEEK' declared const here
    const int DAYS_IN_WEEK = 7;
    ~~~~~~~~~~^~~~~~~~~~~~~~~~

Remember: Constants are often written in CAPITAL_LETTERS so they stand out.

HOME LABS COMMUNITY DASHBOARD