Читаем Справочное руководство по C++ полностью

  default:

   return left;

  }

}

double prim();

double term()

{

 double left = prim();

 for (;;)

  switch (curr_tok) {

  case MUL:

   get_token();

   left *= prim();

   break;

  case DIV:

   get_token();

   double d = prim();

   if (d == 0) return error("divide by 0");

   left /= d;

   break;

  default:

   return left;

  }

}

int number_value;

char name_string[80];

double prim()

{

 switch (curr_tok) {

 case NUMBER:

  get_token();

  return number_value;

 case NAME:

  if (get_token() == ASSIGN) {

   name* n = insert(name_string);

   get_token();

   n-›value = expr();

   return n-›value;

  }

  return look(name_string)-›value;

 case MINUS:

  get_token();

  return -prim();

 case LP:

  get_token();

  double e = expr();

  if (curr_tok != RP) return error(") expected");

  get_token();

  return e;

 case END:

  return 1;

 default:

  return error ("primary expected");

 }

}

token_value get_token()

{

 char ch = 0;

 do {

  if (!cin.get(ch)) return curr_tok = END;

 } while (ch !='\n' && isspace(ch));

 switch (ch) {

 case ';':

 case '\n':

  cin ›› WS;

  return curr_tok=PRINT;

 case '*':

 case '/':

 case '+':

 case '-':

 case '(':

 case ')':

 case '=':

  return curr_tok=ch;

 case '0': case '1': case '2': case '3': case '4':

 case '5': case '6': case '7': case '8': case '9':

 case '.':

  cin.putback(ch);

  cin ›› number_value;

  return curr_tok=NUMBER;

 default:

  if (isalpha(ch)) {

   char* p = name_string;

   *p++ = ch;

   while (cin.get(ch) && isalnum(ch)) *p++ = ch;

   cin.putback(ch);

   *p = 0;

   return curr_tok=NAME;

  }

  error ("bad token");

  return curr_tok=PRINT;

 }

}

int main(int argc, char* argv[])

{

 switch (argc) {

 case 1:

  break;

 case 2:

  cin = *new istream(strlen(argv[1]),argv[1]);

  break;

 default:

  error("too many arguments");

  return 1;

 }

 // insert predefined names:

 insert("pi")-›value = 3.1415926535897932385;

 insert("e")-›value = 2.7182818284590452354;

 while (1) {

  get_token();

  if (curr_tok == END) break;

  if (curr_tok == PRINT) continue;

  cout ‹‹ expr() ‹‹ "\n";

 }

 return no_of_errors;

}

<p>b3_2_6a.cxx</p>

extern void strcpy(char *,char *);

extern void exit(int);

extern int strlen(char *);

char *save_string(char* p)

{

 char* s = new char[strlen(p)+1];

 strcpy(s,p);

 return s;

}

int main (int argc, char* argv[])

{

 if (argc ‹ 2) exit(1);

 int size = strlen(argv[1])+1;

 char* p = save_string (argv[1]);

 delete[size] p;

}

<p>b3_2_6b.cxx</p>

#include ‹stream.hxx›

extern void exit(int);

void out_of_store()

{

 cout ‹‹ "operator new failed: out of store\n";

 exit(1);

}

typedef void (*PF)();

extern PF set_new_handler(PF);

main()

{

 set_new_handler(&out_of_store);

 char *p = new char[100000000];

 cout ‹‹ "done, p = " ‹‹ long(p) ‹‹ "\n";

}

<p>b4_6_8.cxx</p>

// This version of the program does not assume sizeof(int) == sizeof(char*)!

#include ‹stream.hxx›

#include ‹stdarg.hxx›

extern void exit(int);

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
Adobe Flash. Создание аркад, головоломок и других игр с помощью ActionScript
Adobe Flash. Создание аркад, головоломок и других игр с помощью ActionScript

Данная книга посвящена программированию игр с помощью ActionScript. Здесь вы найдете подробные указания, необходимые для создания самых разных игр – аркад, головоломок, загадок и даже игровых автоматов. В тексте приведены исходные коды программ и детальные, доступно изложенные инструкции. Базовые принципы программирования ActionScript рассматриваются на примере игр, однако вы без труда сможете применить полученные знания и для разработки неигровых проектов, таких как Web-дизайн и реклама. Рекомендации Гэри Розенцвейга помогут вам не только придумывать занимательные игры и размещать их на Web-сайте, но и оптимизировать скорость их работы, а также защищать свои творения от несанкционированного копирования. Представленный в книге код несложно изменить для использования в других программах.Книга предназначена для широкого круга читателей – создателей анимационных роликов, художников-оформителей, программистов и разработчиков Web-сайтов. Издание может также выступать в качестве практического пособия по изучению ActionScript.

Гэри Розенцвейг

Программирование, программы, базы данных / Программирование / Книги по IT