Variable Naming Rules in C++

Variable name is a valid identifies which must follow the rules of valid identifier. Some rules for naming identifiers in C++ are as.

Mandatory Naming Rules

The madatory naming rules must be followed by programmer otherwise compiler will generate error at compile time.

  • First character of variable name must be Alphabet or Underscore ( _ ).
  • Digits can be used after Aphabet or Underscore in variable name.
  • Data Type names cannot be used as variable name.
  • Variable name can be used only for single Data Type.
  • Space cannot be used in variable name.

Optional Naming Rules

The optional naming rules can be followed to create more effective and readable variable name. Compiler does not generate error if these rules are not followed.

  • Variable name length not exceed from 31 characters.
  • Variable name should follow same convention in entire program.
  • Variable names should be descriptive.

Examples of valid variable names

#include<iostream>
using namespace std;

int main() {
  int age;
  float _temp;
  double speed1, speed2, speed3;
  char grade;

  return 0;
}

Difference between valid and invalid variable names

No Variable Name Valid / Invalid Invalid Reason
1 int age; valid ----
2 int rank; float rank; Invalid One variable name can only be used for single data type.
3 int 8th_hint; Invalid Number cannot be used as first character of variable name.
4 char grade; valid ----
5 int first count; Invalid Space cannot be use in variable name

 

Comments
Login to TRACK of Comments.