ProgrammingEmbedded C Developer

What do you know about the storage specifiers 'register' and 'auto' in the C language? What is their actual role, is there any point in using them in modern code, and what mistakes can arise from their improper use?

Pass interviews with Hintsage AI assistant

Answer

auto and register are variable storage specifiers in C.

  • auto historically denotes an automatic variable with a scope in the function/block. By default, all local variables are auto, so there is usually no point in writing this explicitly.

  • register asks the compiler to store the variable in the CPU register for faster access. However, modern compilers optimize storage themselves, often ignoring or minimally reacting to this request.

Also, register type variables cannot have an address (&var is prohibited).

Example:

register int counter = 0; auto float sum = 0.0f;

Trick question

Can a pointer be declared to a register variable? For example:

register int x = 5; int *p = &x;

Answer:

No, getting the address of a register variable is not possible—it will result in a compilation error. The register specifier prohibits taking the address of a variable.

Examples of real mistakes due to ignorance of the subtleties of the topic


Story

In an old project, a developer used register for loop variables and then attempted to pass their address to a function: foo(&i);. The code did not compile, requiring removal of the register specifier. The error was only discovered during the build, delaying refactoring.


Story

The team attempted to use register for a large size variable (e.g., a structure). The compiler ignored the request and stored the variable in memory, which did not provide the expected performance boost, leading developers to search for the cause of the slowdown for a long time.


Story

In the code, auto was widely used for local variables, considering it a good style (based on other languages). This cluttered the code, did not affect behavior, complicated reading, and raised questions among colleagues.