40" will probably get you by, it'll just be a little tight. You might go with a round bowl instead of elongated to give you a little more room. You want to be able to stand up from the toilet and not hit your head on the wall. You could take the toilet (if you have it) and set it on the flange with no wax or bolts and see what kind of space you'll have. I don't know what the code would be for your area, you might check with a local code enforcement or a licensed plumber. They usually have a "desired" clearance, and a "minimum" clearance. Personally I would test it, it's kind of a personal preference.
_________________________
The top ten reasons to procrastinate:
1.