Answers so far have covered the problem of cars responding only to their allocated fobs, but the wording of this question implies that you’re wondering how rolling code remotes stay in sync if the button is pressed when the car is too far away to respond.
Rolling code remotes work by adding a further data tag to the transmitted signal that changes with every press of the button. The transmitter and receiver both calculate the next code according to a common algorithm, and the receiver will only respond if the code matches. In this way, the same code is never transmitted consecutively, the idea being that someone cannot snoop and retransmit the code to unlock a car once the owner is gone.
But what happens if the button is pressed while out of range, causing the TX and RX to go out of sync with the next expected code? The transmitter maintains a sync counter that increments each time the code is updated. The count is transmitted to the receiver along with the rest of the codes, and the receiver compares this to its own sync counter. As long as the the count is within an “acceptance window”, the receiver then calculates the expected code based on the difference between the two counters, resyncs to the new count, and responds to the pressed button (lock, unlock, boot release, etc.)
This does mean that if one were to press the button enough times (beyond the acceptance window which may be 1000 or more) while away from the car, sync will be lost and the car will then not respond to the fob, requiring a relearn process.