In the Ethereum wallet there are the estimated gas costs. Why is it only an estimate? Is is possible to calculate the gas costs precisely upfront?
The short answer is: it depends, for some transactions state changes might change the pre calculated gas costs.
It is possible to calculate the gas costs of every transaction given the current state. However - since the state can change until the transaction is finally executed the state can change.
Consider the following code:
if a = true: cheap computation else: expensive computation
Now it is possible that the state of a will change. However - there are a lot of transactions that have always the same costs independent of the state. E.g. a regular value transfer to an account without associated code will always have a fixed cost.