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, wherem
indicates it's a member of the class.m_strName
- A string member variable, withm
indicating its class scope.m_bIsActive
- A boolean member variable, wherem
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;
- Thei
prefix indicates an integer type, andCount
describes its purpose.float fTemperature = 25.0f;
- Thef
prefix indicates a float type, andTemperature
describes its usage.std::string strName = "Alice";
- Thestr
prefix indicates a string type, andName
describes the variable.bool bIsActive = true;
- Theb
prefix indicates a boolean type, andIsActive
describes the state.int* pNode = nullptr;
- Thep
prefix indicates a pointer type, andNode
describes what it points to.class MyClass { int m_iCount; std::string m_strName; bool m_bIsActive; };
- Member variables withm
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.