C++ Tutorial: Variables and Functions

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
Used in and uses: Getting Started

Variables:
Variables are used to store some value. Each variable has a type, for example, a number, letter, sentence, etc. In C++ variables are defined like so:
Code:
<type> <name> = <initial value>;
int x = 0;
where <type> is the type of value that is held, <name> is the identifier used to recognize that variable, and <initial value> is the value it is set to before any functions use the created variable. Variables can be modified via the assignment operator (=), like so: x = 3;
There are a few modifiers available, like const, which means the variable can not be modified. Variable modifiers include the following:
  • const - (const <type> <name> = <initial value>) constant variable, never changes
  • * operator - (<type> * <name> = <initial value>) pointer variable, references a point in memory
  • & operator - (<type> & <name> = <initial value>) reference to a variable, initialized to some variable and allows the user to reference the variable it was initialized to
  • ^ operator - (<type> ^ <name> = <initial value>) handle to a variable (garbage collected (for reference classes)) (these are only in VC++ or windows OS specific C++)
There are also multiple variable types, each of the following can be signed or unsigned, allowing negative or unallowing negative values, ie:
  • int - integer, no decimal number, 4 bytes
  • bool - boolean variable, true or false, 1 byte
  • char - integer, no decimal number, 1 byte
  • short - integer, no decimal, 2 bytes
  • long - integer, no decimal, 8 bytes
  • float - floating point number, decimal points allowed, 4 bytes
  • double - floating point number, decimal points allowed, 8 bytes
  • wide - floating point number, decimal points allowed, 16 bytes
Unsigned/signed variables are written like so:
Code:
unsigned int x = 0;

Arrays:
Arrays are a group of one type of variable, identified by a single number, and they are defined using the [] operator, ie:
Code:
int x [5];
this creates 5 variables of type int (index 0-4), and they are accessed via x[index], ie: x[0].

Arrays can also be initialized to some value, like so:
Code:
int x [] = { 4, 3, 2, 1, 0 };

which would initialize the array x's indexes to the number in the corresponding place, so in that example, x[0] = 4, x[1] = 3, x[2] = 2, x[3] = 1, and x[4] = 0.

Functions:

Functions can be used as any variable of the same type can, however, they run their own actions before returning a value, ie:
Code:
int someFunction () { return 0; }
//calling this function: someFunction(), IE:
int x = someFunction()
the format for a function is: <type> <name> (<arguments>)
every function of a non-void type must return some value of its type before the function ends, the function someFunction will always return 0, so every time it is called, it is the same as using the number 0. Arguments are information sent to the function when calling it, they have specific types and there can be as many arguments as you decide when creating a function. ie:
Code:
int add (int a, int b) { return a + b; }
This function takes 2 numbers of type int, and returns the sum. You can call this function like so:
Using initial values:
Code:
int x = add(1, 1);

Using variables:
Code:
int x = 0;
int y = 1;
int z = add(x, y); //or add(x, 1), etc

Using other functions:
Code:
int x = add(add(1, 1), add(1, 1)); //4

Function Prototypes:

Function prototypes are used to allow the compiler to recognize each function without it's implementation being above the function it is called in.
This allows you to call functions below the function it is referenced in, ie:
Code:
int add (int a, int b);
 
int main ()
{
    int x = add(1, 2);
    return 0;
}
 
int add (int a, int b)
{
    return a + b;
}

This allows you to easily see the main.

Overloaded Functions:

Overloaded functions, are simply functions with the same name, that take different ammounts or types of arguments, even 1 difference is enough. This allows you to easily call different functions using different parameters.

To wrap this up, we are going to make an application that asks the user for a number, then runs a function to output it's square.

Output:
Enter a number: 20
The square of 20 is 400
Press any key to continue...

This is how I would create this application:
Code:
#include <iostream>
 
using namespace std;
 
int square (int);
 
int main ()
{
    cout << "Enter a number: ";
    int x = 0;
    cin >> x;
 
    cout << "The square of " << x << " is: " << square(x) << "\n";
    system("Pause");
    return 0;
}
 
int square (int a)
{
    return a * a;
}
 

UnknowVector

I come from the net ... My format, Vector.
Reaction score
144
GFreak45 said:
^ operator - (<type> ^ <name> = <initial value>) handle to a variable (garbage collected (for reference classes))

Handles are not a part of standard C++. There are, to the best of my understanding--which is somewhat lacking because the C++ ecosystem is pretty confusing--an addition that came from Microsoft's Common Language Infrastructure and are available in C++/CLI language, which is only supported by the Visual Studio family of runtimes and compilers. You should at least make mention of this, though you did say in the other thread that you were targeting visual studio.
 

GFreak45

I didnt slap you, i high 5'd your face.
Reaction score
130
I normally would not but I plan on branching of into a VC++ tutorial chain as well, so i knew it would be needed, ill edit it to make sure that is mentioned
Next tutorial to come out will probably be strings and vectors as well as proper object passing (via reference etc)
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/
  • The Helper The Helper:
    Decided to put up a healthier type recipe to mix it up - Honey Garlic Shrimp Stir-Fry https://www.thehelper.net/threads/recipe-honey-garlic-shrimp-stir-fry.193595/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top