Saturday, May 9, 2009

What is the difference between 'Const' and 'static' in c++?

The 'const' keyword can be used in multiple places. Lets say I have a class called Box that has a method called "Create." My box class also has some member variables for its height width and length. I could have the following method signature:





const Box* Box::Create(const Dimension dim) const


{


// implementation would be here


}





As you can see I used the 'const' keyword a lot here. The first part part: "const Box*" means that the returned value cannot be modified. The second part "const Dimension dim" means the parameter that is passed into the method cannot be altered. The third "const" at the end of the method signature means that I will not modify any member variables on the Box class such as length, width, or height.





The 'const' keyword can also be used on variables to tell the compiler that the value should not change.





The static keyword gives a variable lifetime of the application. It goes into the "static" location in memory. It does not go on the stack and it does not get put on the heap. Heap memory is for dynamically allocated objects and stack data is parameters, return addresses, and local variables.





For more information on static you can look at the link referenced in a previous answer:


http://www.cprogramming.com/tutorial/sta...

What is the difference between 'Const' and 'static' in c++?
static const int num = 10;


const int num2 = 20; absolutely none defference...





The second form, probably. It is shorter.





If you were trying to create a header file that is compilable in both C and C++ code, then maybe it would make sense to use the explicit 'static', since in C constant objects have external linkage by default.





But apparently you are not trying to do that.
Reply:a const variable is constant and cannot be altered. A static variable is stored on the heap rather than on the call stack so it is accessible outside of the current scope and therefore can be shared between different processes.
Reply:A const is a constant, a more semantically correct evolution that used to be #DEFINE macros used in C, just const in C++ is more semantically correct and blends well in a program.





A static is just different, there are two says both correct but do depend on where you use it. Refer to the above wiki to figure it out.
Reply:Here is a web page with some information about static
Reply:They're not comparable.





Static variables live during the whole life of your program. Their scope depends on where they're declared.





Const variables cannot be changed.

surveys

No comments:

Post a Comment