DEV Community

Cover image for C++ Variables, Functions,  Conditionals, and Logic. In VSCode.
JerryMcDonald
JerryMcDonald

Posted on • Updated on

C++ Variables, Functions, Conditionals, and Logic. In VSCode.

In this series, I am reviewing the C++ basics, primarily for those who already understand a coding language and are curious about what makes C++ different.

Here is part one.
Create a C++ program. Run in Visual Studio Code.


Key concepts I am going to review in this blog:

  1. Structuring your .cpp file
  2. void and int type functions
  3. Variable type and scope
  4. C++ Random number generation
  5. Conditionals
  6. Compile and play!

Structuring your .cpp file

Open your C++ folder in Visual Studio Code and create a spock.cpp.
Alt Text

Then create a skeleton for the program.

#include <iostream>
#include <cstdlib>

using namespace std;

void showHand(int num) {
}

int main() {
}
Enter fullscreen mode Exit fullscreen mode

#include <iostream>:
<iostream> is our pre-processor directive providing input and output functionality, <cstdlib> defines several general-purpose functions, including a random number generator, which we will need.

using namespace std
std, which is the C++ standard library, is written into the core C++ language. Declaring our namespace with using namespace std provides scope to our identifiers, improving organization when our code becomes more complex and reducing typing. std::cout becomes cout, and std::rand() becomes rand().

C++, like most coding languages, works from top to bottom, so if we were to create handThrown() under the main() function, then an error would occur.


void and int type functions

When declaring functions, we also need to state what data type we expect returned. In the case of our showHand() function, we do not expect it to return a value; instead, we want it to perform a task, then have control return back to the caller. The void keyword specifies that the function does not return a value.

The C++ standard requires main() to return int. Even if we leave the return statement out, it will return zero, indicating to the operating system that the program ran successfully.


Variable type and scope

Create a user variable and ask the user to input a number.

int user;

  cout << "=================================\n";
  cout << "rock paper scissors lizard spock!\n";
  cout << "=================================\n";

  cout << "1) ✊ rock\n";
  cout << "2) ✋ paper\n";
  cout << "3) ✌️  scissors\n";
  cout << "4) 🦎 lizard\n";
  cout << "5) 🖖 Spock\n\n";

  cout << "shoot: ";

  cin >> user;
Enter fullscreen mode Exit fullscreen mode

C++ is a strongly-typed language. It enforces strict restrictions on intermixing values with different data types. On the other hand, Javascript (created in C++) resembles C++ closely in syntax but is a weakly typed language, meaning its variables still have a type but have looser type rules.

C++ basic data types include:

  • int: integers
  • double: floating-point numbers
  • char: individual characters
  • string: a sequence of characters
  • bool: true/false

The user variable is considered locally scoped. It can be used only by statements inside the main() functions block of code. user is not accessible within our showHand() function. Global variables are declared outside of all the functions and will hold their value throughout your program's lifetime.


C++ Random number generation

Generate a random number between 1 and 5 and assign it to the computer variable.

  srand(time(NULL));
  int computer = 1 + rand() % 5 ;
Enter fullscreen mode Exit fullscreen mode

srand(x) is used to set the seed of the random number generator algorithm used by the function rand(). In combination with (time(NULL), we can use our computers 'continually changing' internal clock to set the seed to a different value on each run.

To produce a random integer within a given range, we can use the following formula:
int number = a + rand( ) % n;
a = the first number in your range
n = the number of terms in your range


Conditionals

C++ supports the usual logical conditions from mathematics and the if-else and switch constructs you also see in C, Java, JavaScript and Visual Basic .

Javascript was written in C++, and the similarities in syntax show in the switch and if-else statements.

Fill your showHand() function with the following switch statement.

void showHand(int num) {
  switch(num) {
    case 1:
    cout << "rock! ✊ \n";
    break;
    case 2:
    cout << "paper! ✋ \n";
    break;
    case 3:
    cout << "scissors! ✌️ \n";
    break;
    case 4:
    cout << "lizard! 🦎 \n";
    break;
    case 5:
    cout << "spock! 🖖 \n";
    break;
  }
}
Enter fullscreen mode Exit fullscreen mode

When writing, functions are an excellent way to reduce code length if a piece of logic is required multiple times. In our program's case, we can use showHand() for both the user's and computer's choice.

  cout << "You chose ";
  showHand(user);

  cout << "The computer chose ";
  showHand(computer);
Enter fullscreen mode Exit fullscreen mode

Here is the logic behind Rock, Paper, Scissors, Lizard, Spock:

  rock > scissors
  scissors > paper
  paper > rock
  lizard > spock
  spock > scissors
  scissors > lizard
  lizard > paper
  paper > spock
  spock > rock
  rock > lizard
Enter fullscreen mode Exit fullscreen mode

With that logic in mind, we can write conditionals for all winning factors or a tie. For the sake of brevity, I did not include them all here.

// note: more code needed; check repo
  if (user == rock && computer == scissors) {

    cout << " You Win!\n";

  } else if (user == computer) {

    cout << " Tie!\n";

  } else {

    cout << "You Lose!\n";

  }
Enter fullscreen mode Exit fullscreen mode

6. Compile and play!

Here is my repo with the full code:
github.com/JerryMcDonald/spock.cpp

In your bash terminal, compile and run the program.

g++ spock.cpp -o spock
./spock
Enter fullscreen mode Exit fullscreen mode

As Sheldon explains, "Scissors cuts paper, paper covers rock, rock crushes lizard, lizard poisons Spock, Spock smashes scissors, scissors decapitates lizard, lizard eats paper, paper disproves Spock, Spock vaporizes rock, and as it always has, rock crushes scissors."

Alt Text

Thanks for reading. If you want to connect, here is my Linked-In

Stay Focused || Love your code

Resources

  1. Learn C++ on Codecademy
  2. Mathbits rand()
  3. stackoverflow (of course)

Top comments (6)

Collapse
 
dynamicsquid profile image
DynamicSquid

C++ is a strongly-typed language. It enforces strict restrictions on intermixing values with different data types. On the other hand, Javascript (created in C++) resembles C++ closely in syntax but is an untyped language, meaning its variables can hold any type of value.

A strongly typed language is different that a untyped language, so you can't really compare the two. I think you're referring to:

Weak: types can be easily converted to other types (JS)
Strong: types can not be easily converted to other types (Java)
Dynamic/Untyped: variables can be assigned to any value, regardless of it's type (Python)
Static: variable types are known at compile time and can not change (C++)

There isn't one set definition for these, so different people might say different things, but this is just the jist of it

Collapse
 
pgradot profile image
Pierre Gradot

Python is not untyped. It is dynamically and strongly typed.

Example:

>>> s = "hello"
>>> type(s)
<class 'str'>
>>> s + 3
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    s + 3
TypeError: can only concatenate str (not "int") to str
>>> s = 3
>>> type(s)
<class 'int'>
Enter fullscreen mode Exit fullscreen mode

We can change the type of s -> dynamic typing

We cannot add a string and a number -> strong typing

Collapse
 
dynamicsquid profile image
DynamicSquid

I thought untyped meant the same as dynamically typed? Like "untyped" not in the sense that there are no types, but "untyped" in the sense that variables aren't bound to a certain type

Thread Thread
 
pgradot profile image
Pierre Gradot • Edited

In that way, I agree. This discussion is interesting: stackoverflow.com/questions/915438... It validates this usage, but it also says that it is a not-so-accurate shortcut.

In my opinion, "untyped" can also refer to cases where there is really "no type". In C++, it is often the case when deal with raw bytes (they are untyped on their own, you can interpret then the way you want) or when you use assembly code (a register simply holds a number, it could be either an int or an enum that fits in an int).

That's why I prefer to use "dynamically typed" when types are actually checked by the language : )

Collapse
 
jerrymcdonald profile image
JerryMcDonald • Edited

Merlin's beard, your right! Operations in "untyped" languages happen directly on bits, with no observation of the type. In Javascript, each operation is bound to a specific type, so you cannot divide an integer by a string. So "weakly-typed" would be a much better description. You rock Squid.

Collapse
 
pgradot profile image
Pierre Gradot • Edited

Declaring our namespace with using namespace std provides scope to our identifiers, improving organization when our code becomes more complex and reducing typing.

Bad! As your code will become more and more complex, using namespace std increases the chances of name clashes. Furthermore, when you see std::something, you know it's from the standard library and you know what it does (well... in many cases you will look for it on cppreference XD). When you simply see something, you may wonder what it is.

Never use using namespace in header files (std being the worst namespace to use).

If you want to use that in source files, be cautious. Don't forget that you can do using std::cout if you are lazy enough and want to save 5 characters.

If you have a modern IDE with shortcuts for templates, you can ease your writing. For instance, in CLion, I have a template so that autocompletion expands cout to std::cout << | << '\n'; with | being my cursor after expansion :)