10 C++ tutorial

10.0.1 I know R but not C++

Summary of how syntax differs between R and C++:

              R code             C++/TMB code

Comments      #                  //                          // Comment symbol
Constants     3.4                Type(3.4);                  // Explicit casting recommended in TMB
Scalar        x = 5.2            Type x = Type(5.2);         // Variables must have type
Arrays        x = numeric(10)    vector<Type> x(10);         // C++ code here does NOT initialize to 0
Indexing      x[1]+x[10]         x(0)+x(9);                  // C++ indexing is zero-based
Loops         for(i in 1:10)     for(int i=1;i<=10;i++)      // Integer i must be declared in C++
Increments    x[1] = x[1] + 3    x(0) += 3.0;                // += -= *= /= incremental operators in C++

It is important to note the following difference compared to R:

Vectors, matrices and arrays are not zero-initialized in C++.

A zero initialized object is created using Eigens setZero():

matrix<Type> m(4,5);

10.0.2 I know C++

TMB specific C++ include: - You should not use if(x) statements where x is a PARAMETER, or is derived from a variable of type PARAMETER. (It is OK to use if on DATA types, however.) TMB will remove the if(x) statement, so the code will produce unexpected results.