정적 변수와 const 변수의 차이점은 무엇입니까?
누군가 a static
와 const
변수 의 차이점을 설명 할 수 있습니까 ?
상수 값은 변경할 수 없습니다. 정적 변수는 인스턴스 나 객체가 아니라 함수 나 클래스에 존재합니다.
이 두 개념은 상호 배타적이지 않으며 함께 사용할 수 있습니다.
짧은 대답 :
A const
는 일단 설정된 값을 수정하지 않겠다는 약속입니다.
static
객체의 수명은 전체 프로그램 실행하고 그것의 값은 프로그램 시작 전에 한번만 초기화되는 변수 수단. 모든 정적은 값을 명시 적으로 설정하지 않으면 초기화됩니다. 정적 초기화의 방식과 타이밍은 지정되지 않습니다 .
C99 const
는 C ++에서 차용했습니다 . 반면에는 static
종종 혼란스러운 의미로 인해 (두 언어 모두에서) 많은 논쟁의 원천이었습니다.
또한 C ++ 0x에서는 C ++ 11까지 static
네임 스페이스 범위에서 개체를 선언 하는 데 키워드 사용이 더 이상 사용되지 않습니다. 이 지원 중단은 다양한 이유로 C ++ 11에서 제거되었습니다 ( 여기 참조 ).
더 긴 답변 : 알고 싶은 것보다 더 많은 키워드 (표준에서 바로) :
C99
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage
int i2; // external linkage, automatic duration (effectively lifetime of program)
int *p = (int []){2, 4}; // unnamed array has static storage
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // static, non-modifiable
void f(int m)
{
static int vla[ m ]; // err
float w[] = { 0.0/0.0 }; // raises an exception
/* block scope, static storage, no-linkage */
static float x = 0.0/0.0; // does not raise an exception
/* ... */
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // automatic storage, non-modifiable
}
inline void bar(void)
{
const static int x = 42; // ok
// Note: Since an inline definition is distinct from the
// corresponding external definition and from any other
// corresponding inline definitions in other translation
// units, all corresponding objects with static storage
// duration are also distinct in each of the definitions
static int y = -42; // error, inline function definition
}
// the last declaration also specifies that the argument
// corresponding to a in any call to f must be a non-null
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);
static void g(void); // internal linkage
C ++
짧은 답변에 명시된 것을 제외하고는 대부분 동일한 의미를 가지고 있습니다. 또한 static
s를 한정하는 매개 변수가 없습니다 .
extern "C" {
static void f4(); // the name of the function f4 has
// internal linkage (not C language
// linkage) and the function’s type
// has C language linkage.
}
class S {
mutable static int i; // err
mutable static int j; // err
static int k; // ok, all instances share the same member
};
inline void bar(void)
{
const static int x = 42; // ok
static int y = -42; // ok
}
static
여기에서 빼 놓은 C ++의 뉘앙스가 몇 가지 더 있습니다. 책이나 표준을 살펴보십시오.
정적 변수 :
- 한 번만 초기화됩니다.
- 정적 변수는 클래스를위한 것입니다 (객체 당 아님). 즉, 메모리는 클래스 당 한 번만 할당되며 모든 인스턴스가이를 사용합니다. 따라서 한 개체가 해당 값을 수정하면 수정 된 값이 다른 개체에도 표시됩니다. (간단한 생각 .. 클래스에 대해 생성 된 객체의 수를 알기 위해 정적 변수를 넣고 생성자에서 ++을 수행 할 수 있습니다.)
- 다른 함수 호출간에 값이 유지됩니다.
상수 변수 :
- Const 변수는 프로그램의 어느 곳에서도 그 값을 변경하지 않을 것이라는 약속입니다. 그렇게하면 불평 할 것입니다.
상수는 변경할 수 없으며 정적 변수는 할당 방법 및 액세스 가능한 위치와 더 관련이 있습니다.
이 사이트를 확인하십시오 .
클래스 컨텍스트의 정적 변수는 클래스의 모든 인스턴스간에 공유됩니다.
함수에서는 영구 변수로 남아 있으므로 예를 들어 함수가 호출 된 횟수를 계산할 수 있습니다.
함수 또는 클래스 외부에서 사용하면 해당 특정 파일의 코드에서만 변수를 사용할 수 있고 다른 곳에서는 사용할 수 없습니다.
그러나 상수 변수는 변경되지 않습니다. 상수와 정적을 함께 사용하는 것은 일종의 상수를 제공하기 위해 클래스 정의 내에서 사용됩니다.
class myClass {
public:
static const int TOTAL_NUMBER = 5;
// some public stuff
private:
// some stuff
};
const
#define
값 문 (예 :)에만 해당됩니다 #define myvalue = 2
. 선언 된 값은 컴파일 전에 변수 이름을 대체합니다.
static
변수입니다. 값은 변경 될 수 있지만 변수는 함수에서 선언 된 경우에도 프로그램 실행 내내 유지 됩니다 . 사용 범위가 선언 된 블록의 범위 인 전역 변수와 동일하지만 값의 범위는 전역입니다.
따라서 정적 변수는 한 번만 초기화 됩니다. 이는 변수가 함수에서 선언 된 경우 특히 중요합니다. 초기화가 함수를 처음 호출 할 때만 발생하도록 보장하기 때문 입니다.
정적의 또 다른 용도는 객체와 관련이 있습니다. 개체에서 정적 변수를 선언하면이 값이 개체의 모든 인스턴스에 대해 동일하다는 효과가 있습니다. 따라서 개체 이름으로 호출 할 수없고 클래스 이름으로 만 호출 할 수 있습니다.
public class Test
{
public static int test;
}
Test myTestObject=new Test();
myTestObject.test=2;//ERROR
Test.test=2;//Correct
C 및 C ++와 같은 언어에서는 정적 전역 변수를 선언하는 것이 무의미하지만 함수와 클래스에서 매우 유용합니다. 관리 언어에서 전역 변수의 효과를 얻는 유일한 방법은 정적으로 선언하는 것입니다.
static은 컴파일 단위 (즉, 단일 C ++ 소스 코드 파일)의 로컬을 의미합니다. 즉, 전역 네임 스페이스에 추가되지 않았 음을 의미합니다. 이름 이 같고 이름 충돌이없는 다른 C ++ 소스 코드 파일에 여러 정적 변수가있을 수 있습니다 .
const는 상수이므로 수정할 수 없습니다.
Static variables are common across all instances of a type.
constant variables are specific to each individual instance of a type but their values are known and fixed at compile time and it cannot be changed at runtime.
unlike constants, static variable values can be changed at runtime.
A static variable can get an initial value only one time. This means that if you have code such as "static int a=0
" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.
A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5
", then this value for "a" will be constant in whole of your program.
const means constant and their values are defined at compile time rather than explicitly change it during run time also, the value of constant cannot be changed during runtime
However static variables are variables that can be initialised and changed at run time. However, static are different from the variables in the sense that static variables retain their values for the whole of the program ie their lifetime is of the program or until the memory is de allocated by the program by using dynamic allocation method. However, even though they retain their values for the whole lifetime of the program they are inaccessible outside the code block they are in
For more info on static variables refer here
Constant variables cannot be changed. Static variable are private to the file and only accessible within the program code and not to anyone else.
static
keyword defines the scope of variables whereas const
keyword defines the value of variable that can't be changed during program execution
Simple and short answer is memory is allocated for static and const only once. But in const that is for only one value where as in static values may change but the memory area remains the same until the end of the program.
Const means “cannot be changed.”
Static means “static instance (in memory) vs dynamic instance (on the stack.)” Static variables exist for the duration of the program. Dynamic ones are created and destroyed as needed.
A variable can be one or both.
static
is used for making the variable a class variable. You need not define a static variable while declaring.
Example:
#include <iostream>
class dummy
{
public:
static int dum;
};
int dummy::dum = 0; //This is important for static variable, otherwise you'd get a linking error
int main()
{
dummy d;
d.dum = 1;
std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;
return 0;
}
This would print: Printing dum from object: 1 Printing dum from class: 1
The variable dum is a class variable. Trying to access it via an object just informs the compiler that it is a variable of which class. Consider a scenario where you could use a variable to count the number of objects created. static would come in handy there.
const
is used to make it a read-only variable. You need to define and declare the const variable at once.
In the same program mentioned above, let's make the dum a const as well:
class dummy
{
public:
static const int dum; // This would give an error. You need to define it as well
static const int dum = 1; //this is correct
const int dum = 1; //Correct. Just not making it a class variable
};
Suppose in the main, I am doing this:
int main()
{
dummy d;
d.dum = 1; //Illegal!
std::cout<<"Printing dum from object: "<<d.dum<<std::endl;
std::cout<<"Printing dum from class: "<<dummy::dum<<std::endl;
return 0;
}
Though static has been manageable to understand, const is messed up in c++. The following resource helps in understanding it better: http://duramecho.com/ComputerInformation/WhyHowCppConst.html
static value may exists into a function and can be used in different forms and can have different value in the program. Also during program after increment of decrement their value may change but const in constant during the whole program.
'program story' 카테고리의 다른 글
__utma는 무엇을 의미합니까? (0) | 2020.12.05 |
---|---|
R을 사용하여 등고선지도 오버레이로 3D 표면도 플로팅 (0) | 2020.12.05 |
스크롤하는 동안 항상 머리글을 정적으로 유지하는 방법은 무엇입니까? (0) | 2020.12.05 |
소급하여 git repo에 --recursive 추가 (0) | 2020.12.05 |
Factory Girl-목적이 무엇인가요? (0) | 2020.12.05 |