Printing my name:



//
// C++ style
// 
#include <iostream>
#include <string>

std::string myname();

int main()
{
  std::cout << "my name is: " << myname() << std::endl;
  return 0;
}

std::string myname()
{
  return "John Cepepe Doe";  // automatic conversion from char * to std::string
}


$ g++ myname.cpp
$ ./a.out
my name is: John Cepepe Doe



//
// C style - wrong
//
#include <iostream>

char *myname();

int main()
{
  std::cout << "my name is: " << myname() << std::endl;
  return 0;
}

char* myname()
{
  return "John Cepepe Doe";  // automatic conversion from char * 
                             // to std::string -- emits warning
}


$ g++ myname.cpp
myname.cpp: In function ‘char* myname()’:
myname.cpp:14:10: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
   return "John Cepepe Doe";  // automatic conversion from char * to std::string
          ^
$ ./a.out
my name is: John Cepepe Doe




//
//  C style with const correctness
//
#include <iostream>

const char *myname();

int main()
{
  std::cout << "my name is: " << myname() << std::endl;
  return 0;
}

const char* myname()
{
  return "John Cepepe Doe";  // automatic conversion from const char * 
                             // to std::string - fine "const safe"
}




Prefer C++ style!
Prefer constant correctness!





Structure of C++ programs
=========================




C++ programs consist of:

- Comments:

  single line comment from // to end of line

  /* multi
     line    
     comments
     // hiding single line comments
   */

  /*
    /*  but must not be nested */
   */

  /*************************************\
  *                                     *
  *  exist in various style and format  *
  *                                     *
  \*************************************/



- Preprocessor directives"

  starting with #

  #ifdef 
  #include
  #error


- C++ tokens:

  - keywords
        lowercase

  - identifyers
        starting with letter (incl _underscore)
        continues with letters or numbers

  - literals
        1    decimal integer literal
        0x14 hexadecimal integer literal
        3.14 floating point literal
        'x'  character literal
        "Hello world" string literal

  - operators
        unary        -2
        binary    2 + 4
        terciary  x<y ? x : y

  - separator
        { } ;   etc.





//
// C++ style
// 
#include <iostream>   <---- preprocessor directvive
#include <string>     <---- preprocessor directvive

std::string myname();    std <-- namespace name: identifier
                         string <-- class name: identifier
                         myname <-- function name: identifier
                         ::     <-- scope: operator
                         ()     <-- function call: operator
int main()               int    <-- type name: keyword
                         main   <-- function name: identifier
                         ()     <-- function call: operator
{                        {      <-- block begin: separator
                         cout   <-- variable: identifier
  std::cout <<           <<     <-- output : operator
                 "my name is: " <-- string literal, type char[13]
            << myname()
            << std::endl;     ; <-- command-end separator
                         return <-- keyword
  return 0;              0      <-- decimal int literal, type int
}

std::string myname()
{
  return "John Cepepe Doe";  // automatic conversion from char * to std::string
}




Keywords
========



we will learn them ...



Identifiers
===========


  - Starts with letter (underscore '_' is a letter)
      continues with letters and digits
      no maximum length

  - Except keywords

  - Case sensitive


   Different conventions:

      camelCaseNotation
      CTypenamesStartsWithUppercase
      under_score_notation

      https://whathecode.wordpress.com/2011/02/10/camelcase-vs-underscores-scientific-showdown/  
      results on February 2015:
          camelCase:  52.5 %
          underscore: 47.5 %


   MACRO_NAMES_ARE_ALL_UPPERCASE by convention


   A paper on this: http://www.cs.loyola.edu/~binkley/papers/icpc09-clouds.pdf



Literals
========

 - Integrals, type + value

   - decimal integral      12    type = int, value = 12
   - octal integral        014   type = int, value = 12
   - hexadecimal integral  0xC   type = int, value = 12

   - long integer          12l   type = long int, value = 12
   - unsigned integer      12u   type = unsigned int, value = 12

   - if longer than integer 10000000 --> long or long long

   - int size knot known ==> the best for the compiler, machine word

 2 <= sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)

  - also exist signed and unsigned versions, e.g. long <==> signed long



 - Characters

  - character   'A'  type = char, value = ascii value of 'A', likely 65
  - escape sequences:
                '\''    single quote
                '\"'    double quote
                '\?'    question mark
                '\\'    backslash
                '\a'    bell (audio)
                '\b'    backspace
                '\f'    form feed -- new page
                '\n'    newline
                '\r'    carriage return
                '\t'    horizontal tab
                '\v'    vertical tab            type = char


  - octal value:        '\377'  -> 11111111
  - hexadecimal value   '\xff'  -> 11111111     type = char
  - unicode value       '\U1234'                type = char16_t (min 16bit)
                        '\U12345678             type = char32_t (min 32bit)

  - wchar_t is the longest character type
  - signed char and unsigned char also exist,
                    but here char not necessary the same as signed char


 1 == sizeof(char) < sizeof(char16_t) <= sizeof(char32_t) <= sizeof(wchar_t)




#include <iostream>

int main()
{
  std::cout << "This is "
            << '\n'
            << "a \"multiline\""
            << '\n'
            << "string"
            << std::endl;
  return 0;
}


$ ./a.out
This is
a "multiline"
string


 - bool

   true   -->  converts to 1
   false  -->  converts to 0


   All non-zero integers are converted to true, and 0 to false
   In conditional expressions all non-zero values are TRUE values!





#include <iostream>

int main()
{
  int n = 5;

  if ( n )
  {
     bool b = n;
     std::cout << "n == " << n << ", b == " << b << std::endl;
     std::cout << std::boolalpha  << "b with boolalpha == " << b << std::endl;
  }
  return 0;
}



$ ./a.out
./a.out n == 5, b == 1
b with boolalpha == true




 - Floating point numbers



 - float        3.14f
 - double       3.14     (as double precision)
 - long double  3.14l



  sizeof(float) <= sizeof(double) <= sizeof(long double)




  Size is not fixed!  (C++ is NOT Java!)


  int ==> best for integral computation, "machine word"
  double ==> best for floating point computation

//
// This is _very_ compiler/platform specific
//
#include <iostream>

int main()
{
  std::cout << sizeof(char) << std::endl;
  std::cout << sizeof(bool) << std::endl;
  std::cout << sizeof(short) << std::endl;
  std::cout << sizeof(long) << std::endl;
  std::cout << sizeof(long long) << std::endl;  // only from C++11
  std::cout << sizeof(float) << std::endl;
  std::cout << sizeof(double) << std::endl;
  std::cout << sizeof(long double) << std::endl;
  std::cout << sizeof(int*) << std::endl;
  std::cout << sizeof("Hello world") << std::endl;

  return 0;
}


$ ./a.out
1
1
2
4
8
8
4
8
16
8
12


  There is a standard library header <limits> containing MIN and MAX values.




Operators
=========


=============================================================================
   | Precedence group  Operator     Description                 Grouping
=============================================================================
1  | Scope              ::          scope qualifier             Left-to-right
-----------------------------------------------------------------------------
2  | Postfix (unary)    ++ --       postfix increment/decrement Left-to-right
   |                    ()          functional forms
   |                    []          subscript
   |                    . ->        member access
-----------------------------------------------------------------------------
3  | Prefix (unary)      ++ --      prefix increment/decrement  Right-to-left
   |                    ~ !         bitwise NOT / logical NOT
   |                    + -         unary prefix
   |                    & *         reference/dereference
   |                    new delete allocation/deallocation
   |                    sizeof      parameter pack
   |                    (type)      C-style type-casting
-----------------------------------------------------------------------------
4  | Pointer-to-member  .* ->*    access pointer                Left-to-right
-----------------------------------------------------------------------------
5  | Multiplicative     * / %       multiply, divide, modulo    Left-to-right
-----------------------------------------------------------------------------
6  | Additive           + -         addition, subtraction       Left-to-right
-----------------------------------------------------------------------------
7  | Bitwise shift      << >>       shift left, shift right     Left-to-right
-----------------------------------------------------------------------------
8  | Relational         < > <= >=  comparison operators         Left-to-right
-----------------------------------------------------------------------------
9  | Equality           == !=       equality/inequality         Left-to-right
-----------------------------------------------------------------------------
10 | And                &           bitwise AND                 Left-to-right
----------------------------------------------------------------------------
11 | Exclusive or       ^           bitwise XOR                 Left-to-right
-----------------------------------------------------------------------------
12 | Inclusive or       |           bitwise OR                  Left-to-right
-----------------------------------------------------------------------------
13 | Conjunction        &&          logical AND                 Left-to-right
-----------------------------------------------------------------------------
14 | Disjunction        ||          logical OR                  Left-to-right
-----------------------------------------------------------------------------
15 | Assignments     =  *=  /=  %=  assignments/compound assign Right-to-left
   |                 += -= >>= <<=
   |                 &=  ^=  |=
   |                    ?:          conditional operator
-----------------------------------------------------------------------------
16 |    Sequencing       ,          comma operator              Left-to-right
=============================================================================




  Operators are used by expressions.
  Precedence and groupping defines the meaning of the expressions.

  Expression evaluation, however, are less strictly defined.



//
// output is not defined
//
#include <iostream>

int main()
{
  int i = 1;
  std::cout << i << ++i << std::endl;

  return 0;
}



$ g++ -ansi -pedantic -Wall expr1.cpp
expr1.cpp: In function ‘int main()’:
expr1.cpp:7:37: warning: operation on ‘i’ may be undefined [-Wsequence-point]

$ ./a.out
22



//
//  use ; for sequence-point (sequence-point is pre C++11)
//
#include <iostream>

int main()
{
  int i = 1;
  std::cout << i;
  std::cout << ++i << std::endl;

  return 0;
}



$ g++ -ansi -pedantic -Wall expr2.cpp

$ ./a.out
12





//
// this can print "f g h" or any other order
//
#include <iostream>

int f() { std::cout << "f "; return 2; }
int g() { std::cout << "g "; return 1; }
int h() { std::cout << "h "; return 0; }

int main()
{
  std::cout << ( f() == g() == h() ) << std::endl;

  return 0;
}




$ ./a.out
f g h 1

 - but may be h g f 1 or g h f 1 or ...




#include <iostream>


int main()
{
  double x = 3.14;
  int y;
  int z;

  z = y = x;
  std::cout << z << std::endl;

  return 0;
}


$ ./a.out
3