Читаем C++ Primer Plus полностью

    int pounds = stonetolb(stone);

    cout << stone << " stone = ";

    cout << pounds << " pounds." << endl;

    return 0;

}

int stonetolb(int sts)

{

     return 14 * sts;

}

Here’s a sample run of the program in Listing 2.6:

Enter the weight in stone: 15

15 stone = 210 pounds.

In main(), the program uses cin to provide a value for the integer variable stone. This value is passed to the stonetolb() function as an argument and is assigned to the variable sts in that function. stonetolb() then uses the return keyword to return the value of 14 * sts to main(). This illustrates that you aren’t limited to following return with a simple number. Here, by using a more complex expression, you avoid the bother of having to create a new variable to which to assign the value before returning it. The program calculates the value of that expression (210 in this example) and returns the resulting value. If returning the value of an expression bothers you, you can take the longer route:

int stonetolb(int sts)

{

      int pounds = 14 * sts;

      return pounds;

}

Both versions produce the same result. The second version, because it separates the computation process from the return process, is easier to read and modify.

In general, you can use a function with a return value wherever you would use a simple constant of the same type. For example, stonetolb() returns a type int value. This means you can use the function in the following ways:

int aunt = stonetolb(20);

int aunts = aunt + stonetolb(10);

cout << "Ferdie weighs " << stonetolb(16) << " pounds." << endl;

In each case, the program calculates the return value and then uses that number in these statements.

As these examples show, the function prototype describes the function interface—that is, how the function interacts with the rest of the program. The argument list shows what sort of information goes into the function, and the function type shows the type of value returned. Programmers sometimes describe functions as black boxes (a term from electronics) specified by the flow of information into and out of them. The function prototype perfectly portrays that point of view (see Figure 2.9).

Figure 2.9. The function prototype and the function as a black box.

The stonetolb() function is short and simple, yet it embodies a full range of functional features:

• It has a header and a body.

• It accepts an argument.

• It returns a value.

• It requires a prototype.

Consider stonetolb() as a standard form for function design. You’ll further explore functions in Chapters 7 and 8. In the meantime, the material in this chapter should give you a good feel for how functions work and how they fit into C++.

Placing the using Directive in Multifunction Programs

Notice that Listing 2.5 places a using directive in each of the two functions:

using namespace std;

This is because each function uses cout and thus needs access to the cout definition from the std namespace.

There’s another way to make the std namespace available to both functions in Listing 2.5, and that’s to place the directive outside and above both functions:

// ourfunc1.cpp -- repositioning the using directive

#include

using namespace std; // affects all function definitions in this file

void simon(int);

int main()

{

    simon(3);

    cout << "Pick an integer: ";

    int count;

    cin >> count;

    simon(count);

    cout << "Done!" << endl;

    return 0;

}

void simon(int n)

{

    cout << "Simon says touch your toes " << n << " times." << endl;

}

The current prevalent philosophy is that it’s preferable to be more discriminating and limit access to the std namespace to only those functions that need access. For example, in Listing 2.6, only main() uses cout, so there is no need to make the std namespace available to the stonetolb() function. Thus, the using directive is placed inside the main() function only, limiting std namespace access to just that function.

In summary, you have several choices for making std namespace elements available to a program. Here are some:

• You can place the following above the function definitions in a file, making all the contents of the std namespace available to every function in the file:

using namespace std;

• You can place the following in a specific function definition, making all the contents of the std namespace available to that specific function:

using namespace std;

• Instead of using

using namespace std;

• you can place using declarations like the following in a specific function definition and make a particular element, such as cout, available to that function:

using std::cout;

• You can omit the using directives and declarations entirely and use the std:: prefix whenever you use elements from the std namespace:

std::cout << "I'm using cout and endl from the std namespace" << std::endl;

Naming Conventions

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

Все книги серии Developer's Library

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

Стивен Прата

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

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