c++【3】 常量、指针、指针变量、变量指针

常量是固定值,在程序执行期间不会改变。这些固定的值,又叫做字面量

常量可以是任何的基本数据类型,可分为整型数字、浮点数字、字符、字符串和布尔值。

常量就像是常规的变量,只不过常量的值在定义后不能进行修改。

1.指针应用(1):

#include 
using namespace std;
 
 //指针应用
int main ()
{
	int a = 20, b = 40;
	int *p1 = &a ,*P2 = &b;
	
	cout <<"a= "<< a <<","<< "b=" <<"b"<

2.指针应用(2):

#include 
using namespace std;
 
//指针应用
int main ()
{
	
	int a = 30 ,int b = 40;
	int *p1 = &a  ,*p2 = &b;
	cout <<"a= " << a << endl;
	cout <<"b= " << b << endl;
	
	cout <<"a= " <<(*p1)<#include 
using namespace std;
 
 //指针应用
int main ()
{
	
	
	int  a = 50;
	int *p = &a;
		
	cout << "a= " <#include 
using namespace std;

/*
	封装一个交换变量的函数,将地址里面的值进行交换
*/ 
void swapfunc(int *p1,int *p2)
{
   int temp = 11;
	 temp  = *p1;
     *p1   = *p2;
	 *p2   = temp;
	
}
 
 //指针应用
int main ()
{
	
	int a ,b;
	int *p1,*p2;
   
    p1 =&a;
    p2 =&b;
	if(a>b)
	swapfunc(pa,pb);	
	cout<<"a= "<< a <<",b="<< b <

6.指针引用---数组

对变量定义另外一个名称,这个名称为该变量的引用

<类型>   &<引用变量名> = <原变量名>;

其中原变量名必须是一个已定义过的变量。如:

int max;

int &bufmax = max;

max = 5;

bufmax = 10;

bufmax = max+bufmax;

//max与bufmax 同一个地址

bufmax并没有重新在内存中开辟单元,只是引用max的单元。max与bufmax在内存中占有同一个地址,即同一个地址两个名字。

#include 
using namespace std;


 //指针应用
int main ()
{
	
	//指针数组
	int a [5] = {11,25,69,30,40};
    int *pa = a; //将数组的首地址赋给指针变量 pa pa= &a[0]
	
	cout <<"\n通过循环输出的数组a元素值: \n";
	for(i=0;i<5;i++)
		cout<<*(pa+i)<<",";
	cout<< endl << endl;	
	
	cout <<"a[0]= "<< *pa << endl;
	*pa = 59;
	cout <<"a[0]= "<< *pa <

7.字符串常量: 

字符串字面值或常量是括在双引号 " " 中的。一个字符串包含类似于字符常量的字符:普通的字符、转义序列和通用的字符。

您可以使用 \ 做分隔符,把一个很长的字符串常量进行分行。

#include
#include

using namespace std;

int main()
{
	string aa = "this is c++ program";
	cout << aa <

8.定义常量:

在C++中,有两种简单的定义常量的方式
        (1)使用 #define 预处理器
        (2)使用 const  关键字

(1) #define 预处理器

#include
#include
using namespace std;

//预处理器定义: #define  identifier  value   格式:#define   定义的名字  代表值    
#define Length 10
#define Width  6
#define Newline '\n'

int main()
{
    
//(1)#define 预处理器
	int area;
	area = Length * Width; //面积 = 长 * 宽
	
	cout << area ;
	cout <

(2) 使用 const  关键字:

//const 格式: const type variable = value;
//使用const前缀声明指定类型的常量 ,意味着不可改

#include
#include
using namespace std;

int main()
{
    const int LENGTH  = 10;
	const int WIDTH   = 7 ;
	const char 	NEWLINE  = '\n';

    int area ;
	
	area = LENGTH * WIDTH ;
	
    cout << area << endl;
	cout << NEWLINE;

    return 0;
}

你可能感兴趣的:(C++,c++,算法,数据结构)