+ 3

Why is const and static used in c++?whats its benefits?

static and const

1st Dec 2016, 7:54 AM
sadiya zainab
sadiya zainab - avatar
3 Respostas
+ 5
There are more than one type of const and static in C++. const variables' values can't be changed after they are assigned. I.e: const x = 2; x = 3; // error, you can't modify a const variable In OOP, there are also const methods. Const methods must not modify class member variables. class Test { public: void increment() const { ++x; // error, cost methods can't alter class members } private: int x; }; Static variables are similar to global variables. Even if they are declared in a local scope, inside a function, they get deleted at the end of the program, not when the control flow leaves the function. #include <iostream> void createX() { static x = 2; } int main() { createX(); std::cout << x; // is correct return 0; } Static functions and variables are only visible inside the file they have been declared in. In OOP, static methods can be called without an object reference, but with the class name only. #include <iostream> class Test { public: static void printHi() { std::cout << "Hi" << std::endl; } }; int main() { Test::printHi(); // correct }
1st Dec 2016, 11:51 AM
David Barzi
David Barzi - avatar
+ 1
challenge me plz 3afakm hh arjoki أرجوكي
1st Dec 2016, 7:28 PM
Rjsrdh Le
Rjsrdh Le - avatar
0
Some value types rely on a fix value, like PI. It's never supposed to change. If you're using a fix value like PI in your code, you want to be safe it's not changable either by you or other coder (like in a project). Also declaring value types as static or const in c++ or other programming languages will safe a little bit of memory on runtime.
1st Dec 2016, 8:19 AM
Patrick Stranz
Patrick Stranz - avatar