If you completely and genuinely forget that you were fasting and eat something, your fast is still considered valid as long as you stop as soon as you realize.
However, if you accidentally consume something in circumstances that could have been avoidable, for example while performing ablution before prayer, then your fast becomes void.
One of the eight steps ...
Your fast is only broken if you had intercourse or semen emission by any means while fasting (not between maghrib and fajr). As fast means to refrain from eating drinking and sexual desires for a defined period of time of the day.