Cpp - Function Global Variables

Introduction

Variables can be defined outside of all functions in a C++ program, including the main() function.

These are called global variables because they are available everywhere in the program.

Variables defined outside of any function have global scope and thus are available from any function in the program, including main().

The following makes use of global variables.

Demo

#include <iostream> 
   //w ww  .  ja  v  a 2  s  . c  om
void convert(); 
   
float fahrenheit; 
float celsius; 
 
int main() 
{ 
   
    std::cout << "Please enter the temperature in Fahrenheit: "; 
    std::cin >> fahrenheit;; 
    convert(); 
    std::cout << "\nHere's the temperature in Celsius: "; 
    std::cout << celsius << "\n"; 
    return 0; 
} 
   
// function to convert Fahrenheit to Celsius 
void convert() 
{ 
    celsius = ((fahrenheit - 32) * 5) / 9; 
}

Result