# Variable that changes itself

I am trying to store a boolean value into a variable with the additional property that the value changes each time the variable is called.

In = var

Out = True

In = var
Out = False


My approach was

var := If[
TrueQ[var],
var = False,
var = True
]


but this is not working. My guess is that is recurring when is calling TrueQ[var]; if this is the case I don't understand why I don't have a recursion limit error.

How can I make my code work?

flip = True;
var := flip = Not[flip]

var
(*False*)

var
(*True*)

var
(*False*)


Here is a way using delayed evaluation and recursive pure function. It allows to only use one variable:

ClearAll[var];
var := Function[Null, With[{res = ! #2}, # := #0[#, res]; res], HoldFirst][var, False]


So that:

var

(* True *)

var

(* False *)

var

(* True *)