Accidential use of classes inside of c style typeless variable arguments list is a common error source. Example:
class MyString {
public:
char *pChars;
int Length;
MyString(char *pChars) {
this->pChars = pChars;
Length = strlen(pChars);
} };
int main() {
MyString s1("Bla1"), s2("Bla2");
printf("%s%s", s1, s2); // This does not but should give a compiler warning/error!
return 0; }
The printf call there receives the two s objects by value. that means all of their members are simply memory copied. But they are interpreted a simple char pointers. Result is a runtime error of course.
I am not asking for a solution to this, but I would like to have something I could add to my class so that the compiler warns me about it or gives an error.
Already tried to declarate but not implement a copy constructor. But it seems that no copy constructor is called. :-(
Please just answer to the question in the title. I do not need a discusson of why you should not use printf or these variable arguments lists - know that.
Thanks for your time.
Variadic functions are functions that can take a variable number of arguments. In C programming, a variadic function adds flexibility to the program. It takes one fixed argument and then any number of arguments can be passed.
Variable length argument is a feature that allows a function to receive any number of arguments.
va_list is a complete object type suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end. If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end.
Variable number of arguments in C++Define a function with its last parameter as ellipses and the one just before the ellipses is always an int which will represent the number of arguments. Create a va_list type variable in the function definition. This type is defined in stdarg. h header file.
Decent compilers (like gcc) check whether printf
arguments match format specifiers in format string.
Just do not forget to add -Wformat
or -Wall
command line option.
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With