整型变量是一个变量

来源:互联网 发布:ubuntu中安装eclipse 编辑:程序博客网 时间:2024/05/16 01:01
变量
一份声明,如×= 5;似乎是明显的。正如你所猜测的,我们将分配5到X的值,但是确切的是什么?是一个变数。
C++中的变量是一块内存可以用来存储信息的一个名字。你可以把一个变量作为一个邮箱,或一间小屋里,我们可以把和检索信息。所有的计算机都有一种叫做随机存取记忆体的记忆体,可供程式使用。当定义一个变量时,一块内存被放置在变量中。
在这一节中,我们只考虑整型变量。整数是整数,如1、2、3、12、16或1。整型变量是一个变量,拥有一个整型值。

为了定义一个变量,我们通常使用声明语句。这里的一个例子,定义变量的×作为一个整数变量(一个可以容纳整型值):

12345678int y;      // define y as an integer variabley = 4;      // 4 evaluates to 4, which is then assigned to yy = 2 + 5;  // 2 + 5 evaluates to 7, which is then assigned to y int x;      // define x as an integer variablex = y;      // y evaluates to 7 (from before), which is then assigned to x.x = x;      // x evaluates to 7, which is then assigned to x (useless!)x = x + 1;  // x + 1 evaluates to 8, which is then assigned to x.


这使它明显,C++将分配值8到变量x。
程序员不倾向于谈论左值或右值的多,因此它不是要记住的重要的。关键的外卖是,在左边的任务,你必须有一个代表一个内存地址(如一个变量)。在赋值的右边的每一个都将被赋值来生成一个值。
初始化和赋值
C++支持两个相关的概念,新的程序员经常搞混了:分配和初始化。
在一个变量被定义后,一个值可以通过赋值操作符(= =符号)分配给它:

2345678910111213// #include "stdafx.h" // Uncomment if Visual Studio user#include <iostream> int main(){    // define an integer variable named x    int x;        // print the value of x to the screen (dangerous, because x is uninitialized)    std::cout << x;     return 0;}


0 0