Constants
Published by
sanya sanya
In C++, constants are values that cannot be modified or changed during the execution of a program. They are used to represent fixed values that should remain constant throughout the program's execution. There are different ways to define constants in C++, including literals, symbolic constants, and macros.
1. Literals:
Literals are direct values used in code. They can be used to represent constants of various types, such as integers, floating-point numbers, characters, and strings.
int num = 10; // Integer literal
float pi = 3.14; // Floating-point literal
char ch = 'A'; // Character literal
string name = "John Doe"; // String literal
Literals are explicit values specified directly in the code.
2. Symbolic Constants:
Symbolic constants are identifiers that represent constant values. They are typically created using the ‘const’ keyword or macros with the ‘#define’ preprocessor directive.
- Constants with ‘const’ keyword:
const int MAX_VALUE = 100;
const float PI = 3.14159;
In the above examples, ‘MAX_VALUE’ and ‘PI’ are symbolic constants created using the ‘const’ keyword. They cannot be modified once assigned a value.
- Constants with macros (‘#define’ preprocessor directive):
#define MAX_VALUE 100
#define PI 3.14159
In this case, ‘MAX_VALUE’ and ‘PI’ are symbolic constants created using macros. Macros are preprocessor directives that perform textual substitution and are not limited to constant values.
When to use each method:
- Literals are suitable for representing small, straightforward constant values directly in the code.
- Symbolic constants (with ‘const’ keyword) are preferred when you need to assign names to constants, enhance readability, and allow type checking.
- Macros (with ‘#define’) are generally discouraged in modern C++ due to their limited type checking and potential for unwanted substitution.
Syntax for symbolic constants with ‘const’ keyword:
const data_type constant_name = value;
Syntax for symbolic constants with macros (‘#define’):
#define constant_name value
Using symbolic constants (with ‘const’ keyword) is generally preferred over macros, as they provide better type safety and can be scoped within namespaces or classes.
Example:
#include
using namespace std;
const int MAX_VALUE = 100;
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (num > MAX_VALUE) {
cout << "Number exceeds the maximum value.\n";
} else {
cout << "Number is within the limit.\n";
}
return 0;
}
In the above code, ‘MAX_VALUE’ is a symbolic constant that represents the maximum allowed value.
Library
WEB DEVELOPMENT
FAANG QUESTIONS