Overloading in C or not?
How does Variable Length Argument lists functions like printf() , scanf(), etc
in C differ from Function Overloading in C++?
And how does the call
printf("Didnt Work %s",s)开发者_如何学运维;
differ from
printf(s,"Didnt Work %s");
where s is defined as:
const char *s="string";
Please Explain.
In
const char *s="string";
printf(s,"Didnt Work %s");
The first argument "string" is interpreted as the format string. It has no insertion codes, so the second parameter won't ever be used. The result will be "string".
OTOH
printf("Didnt Work %s",s);
There is an insertion code, so the second argument gets inserted as a string, the result is "Didn't Work string".
This isn't overloading, because although different argument types are possible just as in overloading, with variable arguments the same function is always called. With overloading different functions are called depending on the argument types.
To answer your second question, others have already for the first.
Variable argument lists in C are very different from overloading in C++. In C you have one function printf
that does perhaps different things with different types of arguments. In C++, with overloading you choose between different functions according to the type of the argument.
Overloading allows for a specific ordering of parameters that the compiler will check for. In C++, if the types don't match for at least one of the function definitions, the compiler will complain. On the other hand, C with variable length arguments, ..., doesn't have this type checking at compile time. The compiler doesn't check any of the parameters to make sure they lined up. you can compile printf("1",3);
on most if not all compilers. Printf will try to read the first argument as a string and will keep reading until it reaches an empty byte signifying the end of a string. This is why variable length argument lists are discouraged.
精彩评论