指针与const

内容见代码注释

示例代码:

// Pointer_Const.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

void inCrement( int *start, int *end )
{
    int *cur = start;

    while( cur != end )
    {
        ++( *cur );
        ++cur;
    }
}

void printNum( const int *start,  const int *end )
{
    const int *cur = start;

    while( cur != end )
    {
        cout << *cur << endl;
        ++cur;
    }
}

//by zhaocl
int main()
{
    /*
    	First Sample

    	int x = 10;

    	//指针指向的值是常量,不能改变,但是指针可以变
    	const int *p1 = &x;
    	++(*p1);	//error
    	++p1;		//ok

    	//指针是常量,不能改变,但是指针指向的值可以改变
    	int * const p2 = &x;
    	++(*p2);	//ok
    	++p2;		//error

    	//指针以及它指向的值都是常量,都不能改变
    	const int * const p3 = &x;
    	++(*p3);	//error
    	++p3;		//error
    */

	//Second Sample
    int numbers[] = { 10, 20, 30 };
    inCrement( numbers, numbers + 3 );
    printNum( numbers, numbers + 3 );

    system( "pause" );
    return 0;
}


猜你喜欢

转载自blog.csdn.net/zhao3132453/article/details/80103968