当前位置:嗨网首页>书籍在线阅读

10-C++语句

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

2.2 C++语句

C++程序是一组函数,而每个函数又是一组语句。C++有好几种语句,下面介绍其中的一些。程序清单2.2提供了两种新的语句。声明语句创建变量,赋值语句给该变量提供一个值。另外,该程序还演示了cout的新功能。

程序清单2.2 carrots.cpp

// carrots.cpp -- food processing program
// uses and displays a variable
#include <iostream>
int main()
{
    using namespace std;
    int carrots;              // declare an integer variable
    carrots = 25;             // assign a value to the variable
    cout << "I have ";
    cout << carrots;          // display the value of the variable
    cout << " carrots.";
    cout << endl;
    carrots = carrots - 1;    // modify the variable
    cout << "Crunch, crunch. Now I have " << carrots << " carrots." << endl;
    return 0;
}

空行将声明语句与程序的其他部分分开。这是C常用的方法,但在C++中不那么常见。下面是该程序的输出:

I have 25 carrots.
Crunch, crunch. Now I have 24 carrots.

下面探讨这个程序。