Constants, References and Strings¶

you can watch parallel the video for C/C++ (german): https://www.youtube.com/watch?v=uKXAJlr7PBY&list=PLEWVM-KBUSpmWSfyoFdD_hLWAY_9tTgi5&index=11

In [1]:
import ROOT
In [2]:
import fortranmagic
%load_ext fortranmagic
import os
import sys

import numpy as np

if sys.platform.startswith("win"):
        # Depends of system, python builds, and compilers compatibility.
        # See below.
    f_config = "--fcompiler=gnu95 --compiler=mingw32"
else:
        # For Unix, compilers are usually more compatible.
    f_config = ""

    # Disable only deprecated NumPy API warning without disable any APIs.
f_config += " --extra '-DNPY_NO_DEPRECATED_API=0'"

%fortran_config {f_config}
New default arguments for %fortran:
	 --extra '-DNPY_NO_DEPRECATED_API=0'

Constants¶

C++¶

In [3]:
%%cpp
const int age=1;
age=0;
cout << "I am "<<age<<"."<<endl;
input_line_56:3:4: error: cannot assign to variable 'age' with const-qualified type 'const int'
age=0;
~~~^
input_line_56:2:12: note: variable 'age' declared const here
 const int age=1;
 ~~~~~~~~~~^~~~~

C¶

constants are the same as in c++

In [4]:
%%cpp
const int age=1;
age=0;
printf("I am %d.",age);
input_line_57:3:4: error: cannot assign to variable 'age' with const-qualified type 'const int'
age=0;
~~~^
input_line_57:2:12: note: variable 'age' declared const here
 const int age=1;
 ~~~~~~~~~~^~~~~

Javascript¶

In [5]:
%%js //the next line is only necessary in jupyter notebooks
element.setAttribute('style', 'white-space: pre;');console.log=function(text){element.textContent+=text+"\n"}

const age=1;
age=0;
console.log("I am "+age+".")

Python¶

no constants exist in Python.

In [6]:
PI=3.14159 #it is only convention to use uppercase for constants
PI="PI"    #but you can change them nevertheless even into other types
print(PI)
PI

Fortran¶

In [7]:
%%fortran 

! program and subroutine exchanged due to jupyternotebook

! program main
subroutine main()
    implicit none
    integer*4,parameter :: c=12
    integer*8,parameter :: c2=13
    print *,c,c2
! end program
end subroutine main
In [8]:
main()
          12                   13

References¶

References are variables that change another variables.

C++¶

In [9]:
%%cpp
int age=42;
int &myage=age;  //this is a reference it needs to be initialized right here
//int &illegal;   //it is not allowed to have an unitialized reference
const int &constref=42; //a number is not allowed in the line above but with const specifier it is ok
myage=40;
//constref=41;        //not allowed
cout <<"I am "<<age<<" old."<<endl;
I am 40 old.

C¶

C does not have references so pointers are used. But be aware of the dangers.

In [10]:
%%cpp
int age=42;
int *myage=&age;
*myage=40;
printf("I am %d old.\n",age);
I am 40 old.
In [11]:
%%cpp
int age=42;
int *myage;    //this is an uninitialized pointer pointing somewhere
//*myage=40;     //now we write to a random memory location
printf("I am %d old.\n",age);
I am 42 old.

Javascript¶

In Javascript it also depends on the type number, boolean, string, null, undefined, symbol are copied array, object, functions are referenced

In [12]:
%%js //the next line is only necessary in jupyter notebooks
element.setAttribute('style', 'white-space: pre;');console.log=function(text){element.textContent+=text+"\n"}

let a=[1,2,3]
let b=a;
b[0]=9
console.log(a)

let c=1
let d=c
d=9
console.log(c)

Python¶

In Python it depends on the type if a copy is made or if the original object is changed. int, float, complex, bool, str and touple are copied as they are immutable objects, meaning its elements cannot be changed.

lists, set, dict, bytearray, files and classes are referenced as they are mutable objects, so that their content ist changed.

In [13]:
a=[1,2,3]
b=a;
b[0]=9
print(a)

c=1
d=c
d=9
print(c)
[9, 2, 3]
1

Fortran¶

In [14]:
%%fortran 

! program and subroutine exchanged due to jupyternotebook

! program main
subroutine main()
    implicit none

    integer*4,target :: age=42
    integer*4,pointer :: myage=>age
    myage=40
    print *,age
! end program
end subroutine main

Strings¶

C++¶

C++ has its own string type. But c type strings are also used quite a bit. Especially string literals as we have used in hello world are actually c type strings.

In [15]:
%%cpp
#include <string>
using namespace std;
string s{"Hello"};     //this is the recommended list-initializer valid since c++11
                       //especially when used with int and double it is safer
int i=2.2;             //gives only compiler warning
//int j{2.2};            //causes compilation error
string t(" how");     //direct initialization
string u=" are you?";  //asignment initialization
string v=t;            //it is a copy
v.resize(3);
cout <<s<<t<<u<<i<<v<<endl;
Hello how are you?2 ho
input_line_61:6:7: warning: implicit conversion from 'double' to 'int' changes value from 2.2 to 2 [-Wliteral-conversion]
int i=2.2;             //gives only compiler warning
    ~ ^~~

C¶

c strings is actually an array of characters. It is used quite oftenly in c++ especially const string literals are safe to use. The last character of the string is a character with value zero.

In [16]:
%%cpp
const char str[]="Hello how are you?";//it is safe to use const string literals
//str[1]="2";                          //as changing the string  the string is not allowed
printf("%s\n",str); //str is actually nothing more than a pointer to the first character
printf("%d",str[sizeof(str)-1]); //the last character of string is character with value zero
Hello how are you?
0
In [17]:
%%cpp
char str[]="Hello how are you?";//it is safe to use const string literals
char str2[]="great";

printf("%s\n",str); //str is actually nothing more than a pointer to the first character
printf("%d",str[sizeof(str)-1]); //the last character of string is character with value zero
Hello how are you?
0

Javascript¶

In [18]:
%%js //the next line is only necessary in jupyter notebooks
element.setAttribute('style', 'white-space: pre;');console.log=function(text){element.textContent+=text+"\n"}

let str="hallo"
let str2=str;
str2="werer"

console.log(str)

Python¶

In [19]:
str="hallo"
str2=str;     
str2=str2[0:2]   #does not
print(str)
print(str2)
hallo
ha

Fortran¶

In [20]:
%%fortran 

! program and subroutine exchanged due to jupyternotebook

! program main
subroutine main()
    implicit none
    character*5 :: str="hallo"
    character*6 :: str2=" great"
    print *,str//str2 ! string concatenation with //
! end program
end subroutine main
In [21]:
main()
 hallo great