When you quickly eat or drink something cold, you experience a sudden onset of a painful headache. This is commonly known as brain freeze, or medically, a sphenopalatine ganglioneuralgia.
Although the cause is not perfectly understood, it is believed to be due to the coldness on the palate (roof of mouth) causing a sudden cooling and rewarming of the sinus capillaries, which causes them to suddenly constrict and then rapidly dilate. Dilation of blood vessels in this area causes pain due to receptors in the vessels. This phenomenon is similar to the cause of a flushed face when exposed to cold wind, and why it sometimes causes headaches.
The only way to prevent a brain freeze is to slowly let the mouth get used to the cold, warming the food or beverage in the mouth instead of quickly swallowing it. Warming the palate with your tongue is another effective way to shorten the duration of a brain freeze.