hungarian notation

Hungarian Notation is a naming convention where the name of a variable or function includes a prefix that denotes its type or intended usage. This convention was designed to help programmers quickly identify the type and purpose of a variable by reading its name.

Hungarian Notation in C++

In C++, Hungarian Notation involves prefixing variable names with letters that indicate their type. This can be particularly useful in large codebases or when working with languages that do not provide explicit type information.

Common Prefixes

Here are some common prefixes used in Hungarian Notation, along with examples of how they might be used in C++:

  • Integer: Prefix with i (e.g., iCount, iIndex)
  • Float: Prefix with f (e.g., fTemperature, fValue)
  • String: Prefix with str (e.g., strName, strAddress)
  • Boolean: Prefix with b (e.g., bIsActive, bFlag)
  • Pointer: Prefix with p (e.g., pNode, pBuffer)

Member Attributes Prefix

In addition to the standard prefixes, Hungarian Notation often includes a special prefix for member variables in classes. This prefix is m, standing for "member". It is used to distinguish member variables from local variables and function parameters.

For example, in a class definition, member variables might be named as follows:

  • m_iCount - An integer member variable, where m indicates it's a member of the class.
  • m_strName - A string member variable, with m indicating its class scope.
  • m_bIsActive - A boolean member variable, where m shows it's a class attribute.

Using the m prefix helps avoid naming conflicts and makes it clear that these variables are part of the class's internal state.

Examples in C++

Here are some examples of variables using Hungarian Notation in C++:

  • int iCount = 0; - The i prefix indicates an integer type, and Count describes its purpose.
  • float fTemperature = 25.0f; - The f prefix indicates a float type, and Temperature describes its usage.
  • std::string strName = "Alice"; - The str prefix indicates a string type, and Name describes the variable.
  • bool bIsActive = true; - The b prefix indicates a boolean type, and IsActive describes the state.
  • int* pNode = nullptr; - The p prefix indicates a pointer type, and Node describes what it points to.
  • class MyClass { int m_iCount; std::string m_strName; bool m_bIsActive; }; - Member variables with m prefix to indicate they are class attributes.

Modern Usage and Alternatives

While Hungarian Notation was popular in the past, modern C++ practices often favor more descriptive naming conventions and explicit type information provided by the language. Many developers now prefer using clear, descriptive variable names without type prefixes.

Modern C++ supports features like type inference and strong type systems, which can reduce the need for Hungarian Notation. Instead, focus on meaningful variable names and use comments to clarify purpose when necessary.


edit this page