|
|
![]() |
| Thread Tools | Search this Thread |
#1
| |||
| |||
How to declare const variable in C++ I have a small code where we are calculating the area of a circular ground. As you can assume this involves "pi" value in your code. Everybody knows that the value of "pi" is constant and that is "3.142". But I don't know how I can declare it as constant variable in C++. I know in C, we declare it above the main() but where is it declared in C++? Can you help me how to declare const variable in C++? |
#2
| |||
| |||
Re: How to declare const variable in C++ It is quiet common that we want some variables in our code that never changes. To declare a variable as constant, we use const keyword to tell compiler that the object or variable is not modifiable. You can directly declare any variable constant directly in your main(). In C++, you never define variable outside any classes. Everything that is defined remain under some class name and it is the main() that is executed first and thus it is better to declare the constant variable over there. |
#3
| |||
| |||
Re: How to declare const variable in C++ Things have changed in C++. Here you do not constant variable outside, everything is categorized, even your declaration. Here you do not define the constant variable using "#define", but you use "const" keyword. The const keyword allows you to specify whether or not a variable is modifiable. The const variable is declared as follows: Code: return_type const variable_name = value; Code: const return_type variable_name = value; |
#4
| |||
| |||
Re: How to declare const variable in C++ Always make sure that you declare the constant variable as "public" and not "private" or "protected" because this will result you a compilation error saying the variable is undefined. This happens because a private or protected member is not accessible in other parts of the code whereas public members are freely accessible to anyone without the need of any object.
__________________ Grand Theft Auto 4 PC Video Game |
![]() |
|
Tags: const variable, cpp |
Thread Tools | Search this Thread |
|
![]() | ||||
Thread | Thread Starter | Forum | Replies | Last Post |
What is the Declare Construct in PHP? | Rob Dizzle | Software Development | 5 | 06-03-2010 03:51 AM |
Differentiate between const and static readonly | KALLIYAN | Software Development | 3 | 17-11-2009 12:52 AM |
Problem of const variable and its reference | KABIRA16 | Software Development | 3 | 04-09-2009 04:45 PM |
Runtime Error 91 : Object Variable or with block variable not set | Ryan21 | Software Development | 2 | 28-08-2009 07:51 PM |
const Obj problem in C++ | Archetype | Software Development | 2 | 25-10-2008 05:58 PM |