Changes

KFLOP C Programs

2,083 bytes added, 21:46, 6 January 2020
/* C Variables */
.
 
===<span id="C Variables" class="mw-headline">C Variables</span>===
C Programs can declare and use various types of variables.  Variables are used to store information.  A variable '''must be declared''' to tell the compiler what type it is '''before''' it can be used.
 
 
3 common types of variables are:
 
'''int''' - 32 bit signed integer (whole numbers only)
 
'''float''' - 32 bit floating point number (~7 digits of precision)
 
'''double''' - 64 bit floating point number (~16 digits of precision)
 
 
Variables can be declared to be '''local''' or '''global'''. "Local" variables are declared inside of any function (including main).  Their "scope" is limited to the function they are declared within.  They are allocated into stack memory and are created when the function is entered and discarded when the function exits.
 
 
The Add function below declares a local variable c as an integer.
 
<pre class="brush:c">// Example to add 2 integer numbers
void Add(int a, int b)
{
int c; // declare a local integer variable
 
c = a + b; // add the integer numbers
printf("sum = %d\n", c); // print the sum
}</pre>
 
"Global" variables are declared outside of any function usually toward the beginning of the program after any included files. Their "scope" is the entire C Program. They are allocated into static memory and are created when the Program begins and discarded when the Program exits.
 
 
The code below declares a global integer variable c outside the Add Function
 
<pre class="brush:c">int c; // declare a global integer variable
 
// Example to add 2 integer numbers
void Add(int a, int b)
{
c = a + b; // add the integer numbers
printf("sum = %d\n", c); // print the sum
}</pre>
 
The advantage of Local variables is that the same name can be used in different functions for different purposes without conflict.
 
The advantage of Global variables is that the value persists for the life of the program and the scope of the entire program and so its value can be read/written from multiple functions or multiple executions of the same function.
 
 
===<span id="C Functions" class="mw-headline">C Functions (Subroutines)</span>===
Bureaucrat, administrator
469
edits