Convenience variables

GDB provides convenience variables that you can use within GDB to hold on to a value and refer to it later. These variables exist entirely within GDB; they aren't part of your program, and setting a convenience variable has no direct effect on further execution of your program. That's why you can use them freely.

Convenience variables are prefixed with $. Any name preceded by $ can be used for a convenience variable, unless it's one of the predefined machine-specific register names (see "Registers"). Value history references, in contrast, are numbers preceded by $. See "Value history."

You can save a value in a convenience variable with an assignment expression, just as you'd set a variable in your program. For example:

set $foo = *object_ptr

saves in $foo the value contained in the object pointed to by object_ptr.

Using a convenience variable for the first time creates it, but its value is void until you assign a new value. You can alter the value with another assignment at any time.

Convenience variables have no fixed types. You can assign to a convenience variable any type of value, including structures and arrays, even if that variable already has a value of a different type. The convenience variable, when used as an expression, has the type of its current value.

show convenience
Print a list of convenience variables used so far, and their values. Abbreviated show con.

One of the ways to use a convenience variable is as a counter to be incremented or a pointer to be advanced. For example, to print a field from successive elements of an array of structures:

set $i = 0
print bar[$i++]->contents

Repeat that command by pressing Enter.

Some convenience variables are created automatically by GDB and given values likely to be useful:

The variable $_ is automatically set by the x command to the last address examined (see "Examining memory"). Other commands that provide a default address for x to examine also set $_ to that address; these commands include info line and info breakpoint. The type of $_ is void * except when set by the x command, in which case it's a pointer to the type of $__.
The variable $__ is automatically set by the x command to the value found in the last address examined. Its type is chosen to match the format in which the data was printed.
The variable $_exitcode is automatically set to the exit code when the program being debugged terminates.