C++: Difference between revisions

From NEOSYS Dev Wiki
Jump to navigationJump to search
 
(One intermediate revision by the same user not shown)
Line 30: Line 30:


programexit()
programexit()
</pre>
==== Syntax highlighting ====
Exodus syntax highlighting can be acquired in nano editor using the following configuration lines. They can also be used as a basis to configure highlighting in other editors.
sudo nano /usr/share/nano/c.
#or maybe
nano ~/.nanorc
and insert somewhere after the line which starts 'syntax "c"'
<pre>
color brightcyan "\<(var|dim|and|or|not|gt|lt|ge|le|eq|ne)\>"
color brightcyan "\<(function|subroutine|gosub|call|in|out|io)\>"
color brightcyan "\<(programinit|programexit|libraryinit|libraryexit)\>\("
color brightcyan "\<(program|a|r|isnum|field2)\>\("
color brightcyan "\<(osgetenv|ossetenv|date|time|timedate|ossleep|ostime|osopen|osclose|osbread|osbwrite|osread|oswrite|osdelete|osrename|oscopy|osflush|oslist|oslistd|osfile|osdir|osmkdir|osrmdir|oscwd|suspend|osshell|osshellread|osshellwrite|stop|abort|perform|execute|chain|logoff|debug|assigned|unassigned|exchange|transfer|print|printl|printt|at|getcursor|setcursor|getprompt|setprompt|input|inputn|rnd|initrnd|mod|abs|pwr|exp|sqrt|sin|cos|tan|atan|loge|integer|floor|round|chr|str|space|count|dcount|index|index2|len|length|match|seq|convert|crop|field|fieldstore|lcase|ucase|lower|raise|quote|squote|unquote|splice|substr|swap|trim|trimb|trimf|converter|cropper|fieldstorer|lcaser|ucaser|lowerer|raiser|quoter|squoter|unquoter|splicer|substrer|swapper|trimmer|trimmerb|trimmerf|oconv|iconv|connect|disconnect|createdb|deletedb|createfile|deletefile|clearfile|listfiles|createindex|deleteindex|listindexes|begintrans|rollbacktrans|committrans|open|read|matread|readv|write|writev|deleterecord|updaterecord|insertrecord|lock|unlock|unlockall|select|clearselect|readnext|selectrecord|readnextrecord|calculate|xlate|replace|extract|erase|insert|locate|locateby|locateusing|remove|sum|replacer|inserter|eraser|output|outputl|outputt|errput|errputl|errputt|logput|logputl|logputt|sqlexec)\>\("
</pre>
</pre>


Line 503: Line 521:
  if (aa eq 1 and bb eq 1) // if aa is not 1 then bb is not checked and could even be unassigned.
  if (aa eq 1 and bb eq 1) // if aa is not 1 then bb is not checked and could even be unassigned.
  if (aa eq 1 or bb eq 1)  // if aa is 1 then bb is not checked and could even be unassigned.
  if (aa eq 1 or bb eq 1)  // if aa is 1 then bb is not checked and could even be unassigned.
=== Troubleshooting ===
==== printl(lcaser("ABC")); //won't compile! ====
Simply use lcase instead of lcaser.
printl(lcase("ABC"));  //result is abc
lcaser is designed to modify a variable so lcaser's parameter must be a variable and not raw data like "ABC".
==== aa(10)=bb; //compiles but doesnt do anything! ====
To replace field 10 of dynamic array aa do one of the following.
replacer(aa,10,bb);
aa.replacer(10,bb);
Exodus doesnt support "aa(10)=" style syntax to replace dynamic array fields.
==== if (aa ^ bb > cc) //won't compile! ====
If the intent is to work like classic multivalue basic code then put brackets to clarify that to the compiler.
if ( (aa ^ bb) > cc)
If instead the intent is aa ^ (bb > cc) then you must pre-calculate the result of bb > cc ...
var dd=bb > cc;
if (aa ^ dd)
... or just wrap it in var()
if (aa ^ var(bb>cc) )
Exodus will not treat the direct result of a logical operation as a character "1" or "0" for the purposes of string concatenation. This is the only deliberate difference from multivalue Basic in Exodus. For why this is so, read about Exodus's concatenation operator.

Latest revision as of 23:23, 4 October 2014

Hello World

After installing Exodus, you can develop Exodus programs from any operating system command line.

This introduction concentrates on simple development from the command line because it is common to all platforms.

Edit

Use Exodus's all-in-one editor+compiler+cataloger 'edic'

edic hello1

edic will give you a skeleton Exodus program which you can develop as you wish.

There must be one and only one "function main()" statement and this is run when the program is started.

By convention, main() must return an integer value. If desired, this can be used to indicate "success" with zero or "failure" with some error number.

The programinit() and programexit() lines are required and provide all the standard multivalue system variables using a simple C++ class macro.

#include <exodus/program.h>

programinit()

function main() {
        printl("hello1 says 'Hello World!'");
        return 0;
}

programexit()

Syntax highlighting

Exodus syntax highlighting can be acquired in nano editor using the following configuration lines. They can also be used as a basis to configure highlighting in other editors.

sudo nano /usr/share/nano/c.
#or maybe
nano ~/.nanorc

and insert somewhere after the line which starts 'syntax "c"'

color brightcyan "\<(var|dim|and|or|not|gt|lt|ge|le|eq|ne)\>"
color brightcyan "\<(function|subroutine|gosub|call|in|out|io)\>"
color brightcyan "\<(programinit|programexit|libraryinit|libraryexit)\>\("
color brightcyan "\<(program|a|r|isnum|field2)\>\("
color brightcyan "\<(osgetenv|ossetenv|date|time|timedate|ossleep|ostime|osopen|osclose|osbread|osbwrite|osread|oswrite|osdelete|osrename|oscopy|osflush|oslist|oslistd|osfile|osdir|osmkdir|osrmdir|oscwd|suspend|osshell|osshellread|osshellwrite|stop|abort|perform|execute|chain|logoff|debug|assigned|unassigned|exchange|transfer|print|printl|printt|at|getcursor|setcursor|getprompt|setprompt|input|inputn|rnd|initrnd|mod|abs|pwr|exp|sqrt|sin|cos|tan|atan|loge|integer|floor|round|chr|str|space|count|dcount|index|index2|len|length|match|seq|convert|crop|field|fieldstore|lcase|ucase|lower|raise|quote|squote|unquote|splice|substr|swap|trim|trimb|trimf|converter|cropper|fieldstorer|lcaser|ucaser|lowerer|raiser|quoter|squoter|unquoter|splicer|substrer|swapper|trimmer|trimmerb|trimmerf|oconv|iconv|connect|disconnect|createdb|deletedb|createfile|deletefile|clearfile|listfiles|createindex|deleteindex|listindexes|begintrans|rollbacktrans|committrans|open|read|matread|readv|write|writev|deleterecord|updaterecord|insertrecord|lock|unlock|unlockall|select|clearselect|readnext|selectrecord|readnextrecord|calculate|xlate|replace|extract|erase|insert|locate|locateby|locateusing|remove|sum|replacer|inserter|eraser|output|outputl|outputt|errput|errputl|errputt|logput|logputl|logputt|sqlexec)\>\("

Save and compile

Make any changes you fancy to the skeleton and save it.

NB Even if you just want to try out the skeleton program exactly as it is without any changes, you must still explicitly save it - otherwise, if you just exit without saving, edic will assume you didn't want a hello1 program, and will cancel. For the default editor (nano), explicit save is usually Ctrl+O.

Upon saving hello1, edic will compile and catalog it automatically.

You can also compile programs directly using 'compile'. 'compile' has a V option (Verbose) to show exactly how 'edic' calls the compiler on your platform in case you wish to customise your own compilation process.

compile hello1 {V}

or manually using your local c++ compiler

g++ hello1.cpp -lexodus -o hello1

Run

To run/open/execute your new hello1 program just type its name.

hello1

and the output is ...

hello1 says 'Hello World!'

Deployment of Compiled Programs

All programs you develop with Exodus's edic or compile commands are stored in the same directory as their source code. They are also copied to a folder in your home directory. This folder is called "Exodus" on Windows and bin or lib on other operating systems.

On Windows, the user who installs Exodus can run any program they develop in Exodus by typing its name at any command prompt. It does not matter what the current working directory is because the Exodus installer permanently adds the Exodus home program directory to the PATH of the user who installs it.

Users other than the user who installed Exodus on Windows, and all users on Linux, Mac or other operating systems, must type "exodus" at a command prompt (or open an Exodus console from an application menu) before they can run any program they develop in Exodus. Once they have done that, it does not matter what the current working directory is because the "exodus" program temporarily adds the Exodus home program directory to the users PATH.

On all operating systems, if there is a similarly named program earlier on in your path (e.g. operating system commands) then you will not be able to run your program because in all cases Exodus adds its path (to your home program directory) to the end of your existing path - not the beginning.

To make any developed Exodus programs available to other users you must arrange for them to be copied to some directory on their path.

Local subroutines

To simulate classic multivalue basic's "gosub/return" in Exodus, you can add additional subroutines and functions between the programinit() and programexit() lines.

You can add them either above or below the "main" function. There is no rule that functions must appear before or above the code that calls them.

Subroutines and functions cannot be nested otherwise compilation will fail. In other words, no function or subroutine can be contain within the body of another.

Simple Example

Here is hello1 modified to call a subroutine that says something.

The word "gosub" is just there for classical clarity. It could be omitted. It could also be replaced by "call" which is also a throwaway word. While gosub and call are interchangeable, if you are going to use them at all, it is probably a good idea to use "gosub funcx()" to indicate internal subroutines and "call funcx()" to indicate external subroutines.

#include <exodus/program.h>

programinit()

function main() {
        printl("hello1 says 'Hello World!'");

        gosub subr1();

        return 0;
}

subroutine subr1() {
        printl("subr1 says 'Hello'");
}

programexit()

output:

hello1 says 'Hello World!'
subr1 says 'Hello'

Subroutine and Function Parameters (Arguments)

Parameter names must be prefixed by "in", "out" or "io" to indicate if they are inbound, outbound or both.

Inbound parameters (prefixed with "in") cannot be amended within the function and the compiler will enforce this. This provides a guarantee to the programmer calling the subroutine or functions that their inbound parameters will not be modified by calling the function. Inbound parameters may be provided by the calling program either as a variable or as raw data like "xyz" or 123 etc.

In/Outbound parameters ("io") must be provided by the calling program in the form of a variable and not raw data. The function can both read and write into these parameters.

Outbound parameters ("out") indicate to the programmer using the function how it works. However, outbound parameters do not actually prevent them being used to provide data to the subroutine or function and are therefore no different from in/outbound parameters. There is no simple way to enforce "write only" parameters using the underlying C++ language.

For special cases, or where performance is critical, the usual C++ parameters are also allowed for example "int arg1" or "const char* arg2" etc.

External functions and subroutines

Editing and compiling external subroutines and functions in Exodus is identical to normal programs except:

  1. the word "program" becomes "library" so we have "library.h", "libraryinit()" and "libraryexit()".
  2. function main can have any parameters you like, for example: "function main(in arg1, in arg2, out arg3)

NB The name of the function internally MUST be main and not the name of the function so we still have "function main(...)" but this time it can have parameter names eg "subroutine main(in instr1, out outstr2)".

External functions and subroutines are implemented as dll or so files and are only loaded into memory the first time that they are used. A missing function or subroutine so or dll file will not cause any failure unless and until it is first used.

Example func1

edic func1
#include <exodus/library.h>

libraryinit()

function main(in arg1, out arg2) {
        printl("func1 says 'Hello World!'");
        arg2="arg1 was "^arg1;
        return 999;
}

libraryexit()

Example prog1 using func1

Compiling func1 created a func1.h file that is required to "glue" func1 into any program that wants to use func1.

To use func1 in any program or external subroutine or function, you need to insert an #include "func1.h" somewhere between "programinit()" and "programexit()" - and not within the body of any function or subroutine.

edic prog1
#include <exodus/program.h>

programinit()

//you must "declare" that we want to use func1
#include "func1.h"

function main() {
        printl("prog1 says 'Hello World!'");

        //we print what func1 returns, and also what func1 returns in arg2
        var arg2;
        printl(   func1("myarg1",arg2)   );
        printl(arg2);

        return 0;
}

programexit()

run prog1

prog1

output:

prog1 says 'Hello World!'
func1 says 'Hello World!'
999
arg1 was myarg1

Functions versus Subroutines

Functions can be used anywhere an expression would be used whereas subroutines can only be used as statements.

The same principle applies to both internal and external subroutines/functions.

Both subroutines and functions can return information in any of their "out" or "io" arguments.

The word "call" or "gosub" before the use of a function or subroutine is optional and can be omitted.

Functions

Functions return a value so you can use them anywhere an expression is required, for example on the right hand side of an assignment.

var yy=funcx(xx);

Even though a function returns a value, the value it returns can be ignored so the following are all equivalent.

call funcx(xx);
gosub funcx(xx);
funcx(xx);

Subroutines

Subroutines do not return a value so they can only be used as statements.

call subrx(xx);   
gosub subrx(xx);  
subrx(xx);        
var yy=subrx(xx); //will not compile

Differences between Exodus's Internal Subroutines and Functions and those of classic multivalue basic

Exodus's internal subroutines and functions are very different from and arguably much better than classic multivalue internal subroutines. They are very similar to external subroutines and functions except they also have access to the global variables of the main program.

Exodus Internal Subroutines and Functions:

  1. can be called with parameters e.g. gosub funcx(xx,yy,zz)
  2. only have access to the main programs global variables - this eliminates a major category of multivalue bugs
  3. functions (not subroutines) can return a result e.g. abc=funcx(xx,yy,zz)

Exodus internal subroutines and functions only have one entry point. In classic multivalue basic you can jump into the middle of any internal subroutine. To simulate this type of coding in Exodus you must create a hierarchy of subroutines or functions that call each other.

The old RETURN TO XYZ syntax is not supported at all and such code must be redesigned to eliminate it.

Moving external subroutines and functions to internal

Exodus allows many classic multivalue basic external subroutines and functions to be reimplemented as internal subroutines and functions. This means that you can now, where appropriate, keep all source code related to one and only one program in a single file. This is a major improvement in source code management.

In classic multivalue basic, if you wanted to implement some function to be used in expressions you were forced to implement it as an external function requiring a separate source code file.

In classic multivalue basic if you wanted to call a subroutine with parameters, or you wanted to be sure that a subroutine would not accidentally overwrite main program variables, you were forced to implement it as an external subroutine or function.

In Exodus the above situations no longer force you to have separate compilation and source files. However you can still make subroutines and functions external exactly as before where that is the best strategy, for example:

  1. to provide some common feature to more than one program
  2. to avoid having to recompile the whole of a large program when you just change part of it
  3. where there is some benefit in not loading all the parts of a program into memory immediately on start-up.

NB Exodus internal subroutines and functions have access to the global variables of the main program so you might want them to make them external to make sure that there is no risk that they touch any global variable.

Exodus Dictionary Subroutines

"S" type file dictionary entries define table columns that are derived by calling a subroutine.

Dictionary subroutines can be executed in two cases.

  1. During a SSELECT command e.g. SELECT USERS WITH AGE_IN_YEARS > 10
  2. In any Exodus program using the Exodus's "calculate" function. e.g. calculate("AGE_IN_YEARS")

Dictionary Subroutine Library Format

Dictionary subroutines are a simplified type of Exodus external subroutine.

A dictionary subroutine is in the format "dict(xyz){...}" where xyz is the dictionary field key *without* quotes and ... is one or more lines of ordinary Exodus source code.

The source code may contain calculate() statements that obtain the results of other dictionary fields.

The source code must result in the variable ANS being set with the required result.

Return statement(s) may be placed anywhere in the code but are not required.

They are slightly different from ordinary external subroutines and do not have programinit()/programexit() clauses. In OO terms, this means that they are simple global functions and not classes, therefore:

  1. No global variables
  2. Any local subroutines or functions must be defined before (above) the dictionary subroutine.

All the subroutines related to one dictionary file go in one "external subroutine library" which can either be written manually or generated automatically from the source code in field 8 of S type dictionaries using the "compile dict_USERS" command.

The library name must be the same as the dictionary file name unless a "USING dictfilename" clause is included in the SSELECT or LIST command.

edic dict_USERS
#include <exodus/dict.h>

dict(AGE_IN_DAYS) {
        ANS=date()-RECORD(1);
}

dict(AGE_IN_YEARS) {
        ANS=calculate("AGE_IN_DAYS")/365.25;
}

Dictionary subroutine variables

Dictionary subroutines have access to the following variables.

When using "calculate(dictid)" the programmer is responsible for setting all these variables (with the exception of ANS) *before* the calculate() expression.

Variable Purpose
ID The database record key.
RECORD The database record
DICT The dictionary file name.
MV The required multivalue number or 0 for all.
ANS Dictionary subroutines return their result in ANS.

Dimensioned Arrays

statement effect
dim arraya(10); create a one dimensional array with 10 elements
dim arrayb(20,30); create two dimensional array with 20x30 elements
dim arraryc=arrayb; create a new array from an existing array;
arrayb=""; initialise all elements to ""
arrayb(15,3)="abc"; set element 15,3 to "abc"
var xx=arrayb(15,3); get element 15,3
arrayd=arrayc; copy the elements of one array to another. If the arrays are of different sizes then only overlapping columns and rows are copied and all others are set to "". If the target array has not been dimensioned then the array is duplicated.
arrayb.redim(15,20); destroy all data and redimension the array to 15x20
var nfields=matparse(record1,arrayb); create a dimensioned array "arrayb" from a dynamic array/string "record1" and return the number of elements.
var record1=matunparse(arrayb); create a dynamic array/string "record1" from a dimensioned array "arrayb"

Dynamic Arrays and < > Brackets

Exodus does not offer the elegant multivalue-style dynamic array extraction and replacement using xx<10> xx<10,2> etc. The same result is achieved, if slightly less elegantly, with a different syntax which is compatible with mainstream languages.

Extracting

Mv Basic Exodus Exodus Alternative
"Explicit" Syntax
Effect
AA=BB<10> aa=bb(10); aa=bb.extract(10); Extract the 10th field of bb into aa
AA=BB<10,2> aa=bb(10,2); aa=bb.extract(10,2); Extract the 10th field, 2nd multivalue of bb into aa
AA=BB<10,2,3> aa=bb(10,2,3); aa=bb.extract(10,2,3); Extract the 10th field, 2nd multivalue, 3rd subvalue of bb into aa

xx(10,2) versus xx.extract(10,2)

Using round brackets "()" to indicate dynamic array extraction is potentially confusing since round brackets are also used for accessing dimensioned arrays.

It is sometimes useful to use the alternative explicit syntax e.g. "aa.extract(10)"

  1. when using dynamic and dimensioned arrays together
  2. when the meaning of round brackets "recordx()" is considered not obvious from the context or variable names.
  3. to be more visually or technically compatible with "curly bracket" family of languages

Replacing

Unfortunately no way has been found to provide both replacement and extraction of dynamic arrays by round brackets using standard C++ language. It is one or the other. Therefore Exodus has chosen to utilise round brackets for the more common operation which is extraction i.e. "aa=bb(10);" and require explicit "replacer" syntax for replacement.

Mv Basic Exodus Effect
AA<10>=BB replacer(aa,10,bb); Replace the 10th field of aa with bb
AA<10,2>=BB replacer(aa,10,2,bb); Replace the 10th field, 2nd multivalue of aa with bb
AA<10,2,3>=BB replacer(aa,10,2,3,bb); Replace the 10th field, 2nd multivalue, 3rd subvalue of aa with bb

NB The following apparently logical syntax will compile but do nothing.

aa(10)=bb; //compiles but doesnt do anything!

Appending

Mv Basic Exodus Effect
AA<-1>=BB replacer(aa,-1,bb); Append bb as a new field of aa.
AA<10,-1>=BB replacer(aa,10,-1,bb); Append bb as a new multivalue of the 10th field of aa.
AA<10,2,-1>=BB replacer(aa,10,2,-1,bb); Append bb as a new subvalue of the 10th field, 2nd multivalue of aa.

NB The following apparently logical syntax will compile but do nothing.

aa(-1)=bb;

Strings and [ ] Brackets

Exodus does not provide elegant multivalue-style substring extraction and replacement using xx[10,2] xx[-3,3] etc. The same result is achieved, if slightly less elegantly, with a different syntax which is compatible with mainstream languages.

Exodus provides a slightly better syntax for single character extraction.

Exodus provides a proper method to extract or replace all characters from a certain character to the end of the string without needing a hack like 999999.

Negative parameters have their usual meaning.

Extracting

Mv Basic Exodus Effect
AA=BB[10,2] aa=bb.substr(10,2); Extract 2 characters of bb starting from the 10th character (into aa)
AA=BB[10,999999] aa=bb.substr(10); Extract all the characters of bb starting from the 10th character (into aa)
AA=BB[-3,3] aa=bb.substr(-3); Extract the last three characters of bb (into aa)
AA=BB[10,1] aa=bb[10]; Extract the 10th character of bb (into aa)
AA=BB[-1,1] aa=bb[-1]; Extract the last character of bb (into aa)

Replacing

Mv Basic Exodus Effect
AA[10,1]=BB splicer(aa,10,1,bb); Replace the 10th character of aa (with bb)
AA[10,2]=BB] splicer(aa,10,2,bb); Replace 2 characters of aa starting from the 10th character (with bb)
AA[10,999999]=BB splicer(aa,10,bb); Replace all characters of aa starting from the 10th character (with bb)

Operators

Operator Precedence

priority operators effect associativity
1 X++  X--  ()  .   evaluate then increment/decrement right
2 ++X  --X  +  -  not increment/decrement then evaluate.
positive, negative, logical negation
left
3 *  /  % multiply, divide, remainder right
4 +  - add, subtract right
5 lt  le  ge  gt compare less than, less than or equal, greater than or equal, greater than right
6 eq  ne compare equal, not equal right
7 ^ concatenate right
8 and logical union right
9 or logical alternative right
10 =  +=  -=  *=  /=  %=  ^= assign, various self update left

Logical and comparative operators

word example symbolic
alternative
and if (aa and bb) &&
or if (aa or bb) ||
not if (not aa) !
eq if (aa eq bb) ==
ne if (aa ne bb) !=
gt if (aa gt bb) >
lt if (aa lt bb) <
le if (aa le bb) <=
ge if (aa ge bb) >=

and/or short circuiting

If the left hand side of an "or" operator is true then the right hand side is not even evaluated. Similarly, if the left hand side of an "and" operator is false then the right hand side is not even evaluated.

This provides a major programming convenience/performance advantage over classic multivalue basic.

if (aa eq 1 and bb eq 1) // if aa is not 1 then bb is not checked and could even be unassigned.
if (aa eq 1 or bb eq 1)  // if aa is 1 then bb is not checked and could even be unassigned.

Troubleshooting

printl(lcaser("ABC")); //won't compile!

Simply use lcase instead of lcaser.

printl(lcase("ABC"));  //result is abc

lcaser is designed to modify a variable so lcaser's parameter must be a variable and not raw data like "ABC".

aa(10)=bb; //compiles but doesnt do anything!

To replace field 10 of dynamic array aa do one of the following.

replacer(aa,10,bb);
aa.replacer(10,bb);

Exodus doesnt support "aa(10)=" style syntax to replace dynamic array fields.

if (aa ^ bb > cc) //won't compile!

If the intent is to work like classic multivalue basic code then put brackets to clarify that to the compiler.

if ( (aa ^ bb) > cc)

If instead the intent is aa ^ (bb > cc) then you must pre-calculate the result of bb > cc ...

var dd=bb > cc;
if (aa ^ dd)

... or just wrap it in var()

if (aa ^ var(bb>cc) )

Exodus will not treat the direct result of a logical operation as a character "1" or "0" for the purposes of string concatenation. This is the only deliberate difference from multivalue Basic in Exodus. For why this is so, read about Exodus's concatenation operator.