Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Discussion

Functions taking a variable number of arguments are a nice commodity, but C-style varargs aren’t the way to get them. Varargs have many serious shortcomings:

  • Lack of type safety: Essentially, the ellipsis tells the compiler: “Turn all checking off. I’ll take over from here and start reinterpret_casting.” (See Item 92.)

  • Tight coupling and required manual cooperation between caller and callee: The language’s type checking has been disabled, so the call site must use alternate ways to communicate the types of the arguments being passed. Such protocols (e.g., printf’s format string) are notoriously error-prone and unsafe because they cannot be fully checked or enforced by either the caller or the callee. (See Item 99.)

  • Undefined behavior for objects of class type: Passing anything but primitive and POD (plain old data) types via varargs has undefined behavior in C++. Unfortunately, most compilers don’t give a warning when you do it.

  • Unknown number of arguments: For even the simplest variable-arguments function (e.g., min) with a variable number of arguments of known type (e.g., int), you still need to have a protocol for figuring out the number of arguments. (Ironically, this is a good thing because it further discourages using varargs.)


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint