Difference between revisions of "C++ Syntax"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
(Read from Console)
(Variables)
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
'C++' is an extended version of 'C', it essentially added more features to allow for Object Oriented Programming. 'C#' is a continuation of 'C++' and was originally developed to replace 'C++', therefore 'C', 'C++', and 'C#' are very similar in many ways and have a few differences.
 +
 
=Comments=
 
=Comments=
 
C++ implements comments by:
 
C++ implements comments by:
Line 80: Line 82:
 
| \' || ' character
 
| \' || ' character
 
|-
 
|-
| \" || Alert or bell
+
| \" || " character
 +
|-
 +
| \? || ? character
 +
|-
 +
| \a || Alert or bell
 
|-
 
|-
 
| \b || Backspace
 
| \b || Backspace
Line 135: Line 141:
  
 
=Variables=
 
=Variables=
Lua uses variables similar to python, you don't need to specify a data type:
+
The main Data types within C++ are:
===Numbers===
+
 
<syntaxhighlight lang=lua>
+
{| class="wikitable"
num = 42  -- All numbers are doubles.
+
|-
</syntaxhighlight>
+
! Data Type !! Keyword
 +
|-
 +
| Boolean || bool
 +
|-
 +
| Integer || int
 +
|-
 +
| Floating Point || float
 +
|-
 +
| Double floating point || double
 +
|-
 +
| Character || char
 +
|}
 +
 
 +
Notice, string is not one of the main types (if you think about it, a string is an array of char).
 +
 
 +
Some of the main types above can also be preceded with:
 +
*signed
 +
*unsigned
 +
*short
 +
*long
  
 
===Strings===
 
===Strings===
<syntaxhighlight lang=lua>
+
See the reading from the console section above.
s = 'walternate'  -- Immutable strings like Python.
+
 
t = "double-quotes are also fine"
+
===Syntax===
u = [[ Double brackets
+
Just like C# you must declare a variable by typing the data type followed by the name of the variable:
      start and end
 
      multi-line strings.]]
 
-- String concatenation uses the .. operator:
 
message = 'Winter is coming, ' .. line
 
</syntaxhighlight>
 
  
===Empty / Null===
+
<syntaxhighlight lang=c++>
<syntaxhighlight lang=lua>
+
#include <iostream>
t = nil -- Undefines t; Lua has garbage collection.
+
using namespace std;
 +
 +
int main () {
 +
  // variable declaration:
 +
  int a;
 +
 +
  // actual initialization
 +
  a = 10;
 +
   
 +
  cout << a;
 +
 +
  return 0;
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Global Variables===
+
Notice in the code above that assignment/initialisation is also the same as in C#, this gives the variable a value and without it the variable will be null.
The default in Lua is that all variables are global (in python all variables are local):
 
<syntaxhighlight lang=lua>
 
  -- Variables are global by default.
 
  thisIsGlobal = 5  -- Camel case is common.
 
</syntaxhighlight>
 
  
===Local Variables===
+
===Local vs Global===
To specify a variable is only local, you need to include 'local' before the variable name:
+
Where you declare your variable determines the scope of the variable. A variable declared within a method will be local and only exist within the method. Declaring a variable outside a method will give it global status. This is the same as C# and is demonstrated below:
  
<syntaxhighlight lang=lua>
+
<syntaxhighlight lang=c++>
  -- How to make a variable local:
+
#include <iostream>
  local line = io.read()  -- Reads next stdin line.
+
using namespace std;
 +
 +
// Global variable declaration:
 +
int g;
 +
 +
int main () {
 +
  // Local variable declaration:
 +
  int a, b;
 +
   
 +
  // actual initialization
 +
  a = 10;
 +
  b = 20;
 +
  g = a + b;
 +
 
 +
  cout << g;
 +
 +
  return 0;
 +
}
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=If Statement=
 
=If Statement=
Lua implements IF statements, but doesn't implement a Switch Case statement. An example if is shown below:
+
C++ If statements are exactly the same as C#.
 
 
<syntaxhighlight lang=lua>
 
if num < 40 then
 
  print('below 40')
 
elseif name ~= 'wayne' then 
 
  -- ~= is not equals.
 
  -- Equality check is == like Python; ok for strs.
 
  io.write('over 40 and Name is wayne\n')  -- Defaults to stdout.
 
else
 
  print('above 40')
 
end
 
</syntaxhighlight>
 
  
 
=Operators=
 
=Operators=
Within if statements and also within loops, the following relational and conditional operates exist:
+
Within if statements and also within loops, the following relational and conditional operates exist (these are the same as C#):
  
 
===Relational===
 
===Relational===
Line 197: Line 229:
 
| == || Equal
 
| == || Equal
 
|-
 
|-
| ~= || Not equal
+
| != || Not equal
 
|-
 
|-
 
| <= || Less than or equal
 
| <= || Less than or equal
Line 212: Line 244:
 
! Operator !!Description !! Example
 
! Operator !!Description !! Example
 
|-
 
|-
| and || Called Logical AND operator. If both the operands are non zero then condition becomes true.||(A and B) is false
+
| && || Called Logical AND operator. If both the operands are non zero then condition becomes true.||(A && B) is false
 
|-
 
|-
| or || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. || (A or B) is true.
+
| <nowiki>||</nowiki> || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. || (A <nowiki>||</nowiki> B) is true.
 
|-
 
|-
| not || Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. || !(A and B) is true.
+
| !|| Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. || !(A && B) is true.
 
|}
 
|}
  
 
=Loops=
 
=Loops=
Just like other languages Lua has the standard 3 types of loop. While will run 0 or more times (may never run), Repeat will run at least once, For will run an exact number of times:
+
Just like other languages Lua has the standard 3 types of loop. While will run 0 or more times (may never run), Repeat (do..while) will run at least once, For will run an exact number of times:
  
===While===
+
Each of the loop structures in C++ are exactly the same as in C#.
<syntaxhighlight lang=lua>
 
-- Blocks are denoted with keywords like do/end:
 
while num < 50 do
 
  num = num + 1  -- No ++ or += type operators.
 
end
 
</syntaxhighlight>
 
 
 
===For===
 
<syntaxhighlight lang=lua>
 
karlSum = 0
 
for i = 1, 100 do  -- The range includes both ends.
 
  karlSum = karlSum + i
 
end
 
 
 
-- Use "100, 1, -1" as the range to count down:
 
fredSum = 0
 
for j = 100, 1, -1 do
 
  fredSum = fredSum + j
 
end
 
 
 
-- In general, the range is begin, end[, step].
 
</syntaxhighlight>
 
 
 
===Repeat / Do While===
 
<syntaxhighlight lang=lua>
 
-- Another loop construct:
 
repeat
 
  print('the way of the future')
 
  num = num - 1
 
until num == 0
 
</syntaxhighlight>
 
  
 
=Functions=
 
=Functions=
===Declaring a function===
 
You can declare a function using the command 'function', the parameters will be within the round brackets '()'. The use of 'local' is not really required:
 
<syntaxhighlight lang=lua>
 
local function add(first_number, second_number)
 
print(first_number + second_number)
 
end
 
 
add(2, 3) -- calling a method
 
</syntaxhighlight>
 
  
===Returning a value===
+
C++ uses the following structure for functions:
You can return a value from a function by using 'return'
+
return_type function_name( parameter list ) {
<syntaxhighlight lang=lua>
+
  body of the function
local function add(first_number, second_number)
+
}
return first_number + second_number
 
end
 
  
print(add(5, 6))
+
If the function has a return_type it will need to return a value of that type:
</syntaxhighlight>
 
  
=Classes - Table Based=
+
<syntaxhighlight lang=c++>
Just like other programming languages, Lua is can be used in an OOP way. Lua calls '{}' tables or meta tables, but they are the same as a class really:
+
int TimesTwo(int num)
 
+
{
===Define a class===
+
   return num*2;
<syntaxhighlight lang=lua>
+
}
-- Meta class, class defined with {}, variables can be set like 'area'
 
Shape = {area = 0}
 
 
 
-- Base class is named, followed by ':' to create a method for the class
 
function Shape:new (o,side)
 
  o = o or {} -- if an object is passed, use it or create an empty one
 
   setmetatable(o, self)
 
  self.__index = self
 
  side = side or 0 -- if side is passed, use it or set side to 0
 
  self.area = side*side;
 
  return o
 
end
 
 
 
-- Base class method printArea
 
function Shape:printArea ()
 
  print("The area is ",self.area)
 
end
 
 
</syntaxhighlight>
 
</syntaxhighlight>
  
===Creating an object===
+
You could call this function by using the function name and by providing it with its parameters:
<syntaxhighlight lang=lua>
 
-- Creating an object
 
myshape = Shape:new(nil,10)
 
  
--to access the methods of the object you need to use ':'
+
<syntaxhighlight lang=c++>
myshape:printArea()
+
cout << TimesTwo(10) << endl;
</syntaxhighlight>
+
int a;
 
+
a = TimesTwo(15);
===Inheritance===
+
cout << a << endl;
<syntaxhighlight lang=lua>
 
Square = Shape:new()
 
 
 
-- Derived class method new
 
 
 
function Square:new (o,side)
 
  o = o or Shape:new(o,side) -- if an object is passed, use it or create a new shape
 
  setmetatable(o, self)
 
  self.__index = self
 
  return o
 
end
 
</syntaxhighlight>
 
 
 
You can override an inherited method by redeclaring it:
 
<syntaxhighlight lang=lua>
 
-- Derived class method printArea
 
 
 
function Square:printArea ()
 
  print("The area of square is ",self.area)
 
end
 
</syntaxhighlight>
 
 
 
=Classes - Closure Based=
 
Lua can implement classes in a second way:
 
===Define a Class===
 
<syntaxhighlight lang=lua>
 
function MyClass(init)
 
  -- the new instance
 
  local self = {
 
    -- public fields go in the instance table
 
    public_field = 0
 
  }
 
 
 
  -- private fields are implemented using locals
 
  -- they are faster than table access, and are truly private, so the code that uses your class can't get them
 
  local private_field = init
 
 
 
  function self.foo()
 
    return self.public_field + private_field
 
  end
 
 
 
  function self.bar()
 
    private_field = private_field + 1
 
  end
 
 
 
  -- return the instance
 
  return self
 
end
 
</syntaxhighlight>
 
 
 
===Creating an Object===
 
Creating and using an instance can be done with:
 
 
 
<syntaxhighlight lang=lua>
 
local i = MyClass(5)
 
print(i.foo()) --> 5
 
i.public_field = 3
 
i.bar()
 
</syntaxhighlight>
 
 
 
===Inheritance===
 
This is the base class, and below a subclass derived from it:
 
 
 
<syntaxhighlight lang=lua>
 
function BaseClass(init)
 
  local self = {}
 
 
 
  local private_field = init
 
 
 
  function self.foo()
 
    return private_field
 
  end
 
 
 
  function self.bar()
 
    private_field = private_field + 1
 
  end
 
 
 
  -- return the instance
 
  return self
 
end
 
 
 
function DerivedClass(init, init2)
 
  local self = BaseClass(init)
 
 
 
  -- Public fields can be added to the derived version
 
  self.public_field = init2
 
 
 
  -- this is independent from the base class's private field that has the same name
 
  -- the derived value would be self.private_field
 
  local private_field = init2
 
 
 
  -- save the base version of foo for use in the derived version
 
  local base_foo = self.foo
 
 
 
  -- this function overrides the derived version
 
  function self.foo()
 
    return private_field + self.public_field + base_foo()
 
  end
 
 
 
  -- return the instance
 
  return self
 
end
 
 
</syntaxhighlight>
 
</syntaxhighlight>

Latest revision as of 11:56, 14 June 2019

'C++' is an extended version of 'C', it essentially added more features to allow for Object Oriented Programming. 'C#' is a continuation of 'C++' and was originally developed to replace 'C++', therefore 'C', 'C++', and 'C#' are very similar in many ways and have a few differences.

Comments

C++ implements comments by:

/* This is a comment */

/* C++ comments can also
   * span multiple lines
*/

// Single line comment also

Write to Console

Writing to the console is a little more complicated than other languages:

#include <iostream>
using namespace std;

main() {
   cout << "Hello World"; // prints Hello World
   
   return 0;
}

You can also use 'endl' to have a new line:

#include <iostream>
using namespace std;

int main() {
   cout << "Hello World" << endl;
   cout << "Hola Mundo"  << endl;
   
   return 0;
}

You can also concatenate using the '<<' symbols:

#include <iostream>
using namespace std;

main() {
   cout << "Hello World " << 0 <<endl; // prints Hello World followed by a 0
   
   return 0;
}

This method can be used to concatenate variable into your output (ie replace '0' with a variable name).

Escape Characters

These can also include escape characters in the string, eg '\n':

#include <iostream>
using namespace std;

main() {
   cout << "Hello\nWorld"; // prints Hello followed by a new line and then World
   
   return 0;
}

Here is a list of the escape characters available:

Escape sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh . . . Hexadecimal number of one or more digits

Read from Console

C++ can read from the keyboard (ie Console.ReadLine() in C# or input() in Python), This uses the 'cin' command. The example is for will read an integer (notice the direction of the '>>' is swapped for inputs):

#include <iostream>
using namespace std;

int main ()
{
  int i;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  return 0;
}

Strings are handled differently, because using 'cin' a space is considered to be terminating character. using this method you can only enter a single word. So you need to do this instead:

#include <iostream>
#include <string> //added this include for handling strings
using namespace std;

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr); //getline is passed cin and the string to read in
  cout << "Hello " << mystr << endl;

  return 0;
}

Variables

The main Data types within C++ are:

Data Type Keyword
Boolean bool
Integer int
Floating Point float
Double floating point double
Character char

Notice, string is not one of the main types (if you think about it, a string is an array of char).

Some of the main types above can also be preceded with:

  • signed
  • unsigned
  • short
  • long

Strings

See the reading from the console section above.

Syntax

Just like C# you must declare a variable by typing the data type followed by the name of the variable:

#include <iostream>
using namespace std;
 
int main () {
   // variable declaration:
   int a;
 
   // actual initialization
   a = 10;
 
   cout << a;
 
   return 0;
}

Notice in the code above that assignment/initialisation is also the same as in C#, this gives the variable a value and without it the variable will be null.

Local vs Global

Where you declare your variable determines the scope of the variable. A variable declared within a method will be local and only exist within the method. Declaring a variable outside a method will give it global status. This is the same as C# and is demonstrated below:

#include <iostream>
using namespace std;
 
// Global variable declaration:
int g;
 
int main () {
   // Local variable declaration:
   int a, b;
 
   // actual initialization
   a = 10;
   b = 20;
   g = a + b;
  
   cout << g;
 
   return 0;
}

If Statement

C++ If statements are exactly the same as C#.

Operators

Within if statements and also within loops, the following relational and conditional operates exist (these are the same as C#):

Relational

Symbols Explanation
== Equal
!= Not equal
<= Less than or equal
>= Greater than or equal
< Less than
> Greater than

Conditional

Operator Description Example
&& Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false
|| Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

Loops

Just like other languages Lua has the standard 3 types of loop. While will run 0 or more times (may never run), Repeat (do..while) will run at least once, For will run an exact number of times:

Each of the loop structures in C++ are exactly the same as in C#.

Functions

C++ uses the following structure for functions:

return_type function_name( parameter list ) {
  body of the function
}

If the function has a return_type it will need to return a value of that type:

int TimesTwo(int num)
{
   return num*2;
}

You could call this function by using the function name and by providing it with its parameters:

cout << TimesTwo(10) << endl;
int a;
a = TimesTwo(15);
cout << a << endl;