The Art of Global Variables in C++

2025-02-10

This article explores effective techniques for using global variables in C++. The author argues that global variables aren't inherently bad; the key lies in their proper application. The article presents advantages and disadvantages, outlining four rules: 1. Make it hard to misuse; 2. Restore original values after changing observable states; 3. Don't return references or pointers to internal state; 4. Don't make it hard to test. Through code examples, the author demonstrates correct usage and potential pitfalls, recommending thread-local variables for multi-threading.

Read more
Development Global Variables

Global Variables: Not the Devil You Think They Are

2025-02-03

This article uses a simple counter example to demonstrate how avoiding global variables can unexpectedly lead to bugs. The author argues that the problem isn't global variables themselves, but the hidden nature of data access – "action at a distance". Different variable types are analyzed, and the article explores ways to use global variables appropriately in specific scenarios, such as encapsulating them into functions or using types that only allow append operations, thus preventing issues caused by "action at a distance".

Read more