Variable and Constant Declarations
Variables are the same in C/C++ as in C#. They are used to store a value that you can change as the program runs. Constants are also the same — they are used to store a value that can not be changed
The names of the basic types are also the same in C/C++ as they were in C#:
int
for whole numbers.double
for real numbers.string
for text.char
for a single character.bool
for boolean values. In C/C++, there are constants fortrue
andfalse
, but 0 is also considered false with any other value considered to be true.
Example
Here is the example from the variables page rewritten in C/C++. Notice that the logic is exactly the same, and that the code is only superficially different. Have a read through and compare it with the original code.
Key changes include:
- Using different libraries:
- We can access the SplashKit library using
#import "splashkit.h
. - We need
using std::to_string;
andusing std::stod;
to gain access to these C++ functions from the standard (std
) library.
- We can access the SplashKit library using
- Changing names of identifiers:
WriteLine
is nowwrite_line
.Write
becomeswrite
.
C/C++ also lacks the elegant string interpolation feature we had in C#. This means you cannot easily embed values within your strings. Instead, can use to_string
to convert numbers into strings, and then use string concatenation (+
) to combine different strings together.
Have a go at coding this up yourself, and run the program to see it working. The thought process to create this is the same as before, you just need to switch some details.