Subj : Re: Any help on why? To : borland.public.cpp.borlandcpp From : waking Date : Sun Jul 11 2004 03:35 am On Thu, 08 Jul 2004 18:58:29 -0700, Bob Gonder wrote: >I've yet to see a compiler do anything other than pass the string to the RTL. Now that I have demonstrated that some compilers *do* actually parse the format string being passed to the printf function, it's time to consider the possible effects of mismatches. The compiler writers are under *no* obligation to pass on code to be compiled which it has detected violates some syntactical rule. They may handle it in *any* way they deem most appropriate. Some possible scenarios, given a mismatch between format specifiers and arguments being passed: (1) Pass on both the format string and the variable arguments exactly as written in the source. This *may* be the most attractive option, as it entails the least amount of programming for the compiler writers. It has the down side of resulting in potentially confusing and unpredictable consequences when the program is run. (2) Silently alter the format string before passing it on to the RTL function, so that a mismatched type specifier is replaced by one of the proper type for the matching variable argument. e.g. - If %d is encountered for a float arg, replace the %d with %f before passing on the string. This ensures safer execution of the RTL function, and minimizes any "corruption" of the resultant output. (3) Silently cast the mismatched variable argument so that it matches the type specifier in the format string. e.g. - If %f is encountered with a correspond- ing integer variable, supply an implicit typecast for the variable: (float) intvar This approach would be limited by any language constraints on casting between different types. e.g. - Given this: int myint = 44; float myflt = 1.5; printf("%f\t%d\n", myint, myflt); // vars don't match type specifiers issue warnings and then dynamically change to this: printf("%f\t%d\n", (float)myint, (int)myflt); // now they do This would give much more predictable and easily interpreted results when run, albeit the order of appearance of the output fields may seem switched from what the programmer expected or intended. Summary: While *most* (even all) compilers currently available *may* adopt approach (1) above, there is *no* guarantee that they do or that future compilers or future versions of current compilers will use the same method. All bets are off when you have source code which transgresses the specified syntax or grammar of the language or compiler-specific language extensions. Proceed with (great) caution when making assumptions about compiler behavior in such cases, and don't generalize from empirical results obtained in specific circumstances. -- Wayne A. King (waking@idirect.com, Wayne_A_King@compuserve.com) .