Skip to content

More Basics

:material-circle-edit-outline: 约 79 个字 :fontawesome-solid-code: 54 行代码 :material-clock-time-two-outline: 预计阅读时间 1 分钟

4.2 Ellipses (...)

Ellipses (...) can be used as the last parameter of a function to denote zero or more arguments of unknown type. The compiler suspends type checking for these parameters. For example,

/*
 *  TestEllipses.cpp
 */
#include <iostream>
#include <cstdarg>
using namespace std;

int sum(int, ...);

int main() {
   cout << sum(3, 1, 2, 3) << endl;       // 6
   cout << sum(5, 1, 2, 3, 4, 5) << endl; // 15

   return 0;
}

int sum(int count, ...) {
   int sum = 0;

   // Ellipses are accessed thru a va_list
   va_list lst;  // Declare a va_list
   // Use function va_start to initialize the va_list,
   // with the list name and the number of parameters.
   va_start(lst, count);
   for (int i = 0; i < count; ++i) {
      // Use function va_arg to read each parameter from va_list,
      // with the type.
      sum += va_arg(lst, int);
   }
   // Cleanup the va_list.
   va_end(lst);

   return sum;
}

4.3 Scope Resolution Operator

The symbol :: is known as scope resolution operator. If a global variable is hidden by a local variable of the same name (of course not recommended), you could use the scope resolution operator to retrieve the hidden global variable. For example,

//  TestScopeResolutionOperator.cpp
#include <iostream>
using namespace std;

// Global variable
int x = 5;

int main() {
   // A local variable having the Same name as a global variable,
   // which hides the global variable
   float x = 55.5f;

   // Local
   cout << x << endl;

   // Use unary scope resolution operator to retrieve the global variable
   cout << ::x << endl;

   return 0;
}