2016-07-17 3 views
0

의심의 여지가 있습니다. 는 아래의 C 프로그램함수에서 const 매개 변수를 사용하는 C 프로그래밍

int main(void){ 

    unsigned int consttest_var = 1; 
    unsigned int i; 
    for(i = 0; i<10; i++){ 
    consttest_var++; 
    consttest_func(consttest_var); 
    } 
    return 0; 
} 

    void consttest_func(const unsigned int consttest_var1){ 
    printf("\n%d", consttest_var1); 
} 

나는 위의 코드를 시도하고 내가 2,3,4으로 consttest_var1 가치를 가지고 .... 10를 참조하십시오. const로 선언되었을 때 consttest_var1이 값을 인쇄해야하는 이유는 무엇입니까? 난 그것이 읽기 전용으로 오류를 던질 것으로 기대했다. 아무도 이것을 설명 할 수 있습니까?

+1

함수에서 상수가 될 시간을 선언하고 시스템 시계가 중지되는지 확인하려고합니다. – stark

답변

1
unsigned int consttest_var = 1; 

여기서는 비 const로 선언했습니다. 당신이 consttest_func(consttest_var)로 보내

는, 함수는 선언 const unsigned int을 기대 : 함수 자체가 const를하기 때문에, 인수를 변경할 수 없습니다 void consttest_func(const unsigned int consttest_var1)

하지만, 함수의 범위를 외부 변수 ISN ' 당신의 functoin가 CONST 변수를 예상하고이를 수정하지 않습니다 - - t의 CONST는, 따라서, 일을 정리해

을 수정할 수는

더 const를

에 대해 읽어 this을 볼 수로

참고 : 변수를 const로 선언한다고해서 다른 곳에서 (인수로) 수정할 수 없다는 의미는 아닙니다. 예를 들어,이 코드는 비록 const를 얻고 그것을 증가 시키더라도 컴파일 할 것입니다. 왜냐하면 a가 const으로 정의되었지만 함수 f가 가져 오는 것이고 복사본은 수정 가능하기 때문입니다.

#include <stdio.h> 
int f(int a){ 
a++; 
return a; 
} 

int main(){ 
    const int a = 1; 
    printf("\n%d",f(a)); 
    return 0; 
} 
1

나는 읽기 전용으로 오류를 던지는 것이다 기다리고 있었다.

void consttest_func(const unsigned int consttest_var1){ 
    printf("\n%d", consttest_var1); 
} 

귀하의 consttest_func 정말 읽기 전용으로 그래서는 어떤 오류가 발생하지 않습니다, 매개 변수 consttest_var1 수정하지 않습니다.

실제로 consttest_var1++;과 같은 명령문을 사용하여 consttest_func 내부의 매개 변수를 수정하면 예상대로 read-only parameter이 표시됩니다.

0

const 변수 consttest_var1은 consttest_func 함수에 대해 로컬로 선언됩니다. 기능이 끝나면 consttest_var1이 범위를 벗어납니다.

함수를 다시 호출하면 새 const consttest_var1에 스택의 새 공간이 할당되고 초기화 후에는 변경되지 않습니다.

0

주된 이유는 함수가 호출 될 때마다 새 값이 전달되기 때문입니다. 그리고 프로그램에서 변수 'consttest_var1'이 상수인지 여부는 중요하지 않습니다. 함수가받은 값만 표시하기 때문입니다. 그리고 상수 변수는 값을 초기화 한 후에는 수정할 수없는 변수입니다. 프로그램의 주석을 따르십시오 ...

  int main(void) 
      { 
       unsigned int consttest_var = 0; 
       unsigned int i; 
       for(i = 0; i<10; i++){ 
       consttest_var++; 
       consttest_func(consttest_var); 
       } 
       return 0; 
      } 
       void consttest_func(const unsigned int consttest_var1) 
      { 
       consttest_var1=3; //suppose if u write this line. 
       /* then this line will throw an error that u were talking about 
       i.e. assignment of read only parameter 
       as u are modifying the value of a constant variable */ 
       printf("\n%d", consttest_var1); 
      } 
관련 문제