how to declare a variable in .cpp file that has no class and it should have variable…
- User
how to declare a variable in .cpp file that has no class and it should have variable declaration and definition
- Assistant
In C++, you can declare and define a variable in a
.cppfile outside of any class by simply specifying the type and the variable name followed by an optional initialization. Such variables, when declared outside of any function or class, have global scope and static storage duration.Here is an example of how to declare and define a global variable in a
.cppfile:// Example of a global variable in a .cpp file #include <iostream> // Declare and define the global variable int globalVariable = 42; // Function that uses the global variable void printGlobalVariable() { std::cout << "The value of globalVariable is: " << globalVariable << std::endl; } int main() { // Print the initial value of the global variable printGlobalVariable(); // Modify the global variable globalVariable = 100; // Print the modified value of the global variable printGlobalVariable(); return 0; }