The fourth part of the translation is
D Programming Language Tutorial by
Ali Çehreli .
Other parts:
Variables
Specific concepts that are presented in the program are called
variables . A value like
air temperature or a more complex object, like
a car engine , can be variable in a program.
Each variable has a specific type and a specific value. Most variables also have names, but some are anonymous.
')
As an example of a variable, we can consider the concept of the
number of students in a school. Since the number of students is an integer,
int is a suitable type, and the
studentCount will be a sufficiently descriptive name.
According to the syntax rules, a variable begins with its type followed by a name. Introducing a variable into a program is called a
definition . Once a variable is defined, its name begins to represent its value.
import std. stdio ;
void main ( )
{
// Definition of a variable; this definition
// indicates that the studentCount type is int:
int studentCount ;
// The name of the variable becomes its value:
writeln ( "Present" , studentCount , "students." ) ;
}
The output of this program:
0
As can be seen from this line, the
studentCount value is 0. According to the table of fundamental types from the last chapter: the initial value of
int is 0.
Notice that the
studentCount string
does not appear in the output. In other words, the program does not display "Present studentCount pupils".
Variable values are changed with the
= operator. Operator
= assigns new values to variables, and for this reason is called
the assignment operator :
import std. stdio ;
void main ( )
{
int studentCount ;
writeln ( "Present" , studentCount , "students." ) ;
// Assigning the value 200 to the studentCount variable:
studentCount = 200 ;
writeln ( "Now present," studentCount , "students." ) ;
}
0 . 200 .
When the value of a variable is known at the time of the definition, the value of the variable can be assigned simultaneously with its definition. This is an important principle; this makes it impossible to use a variable until the value assigned to it is assigned:
import std. stdio ;
void main ( )
{
// Simultaneous definition and value assignment:
int studentCount = 100 ;
writeln ( "Present" , studentCount , "students." ) ;
}
100 .
Exercises
- Define two variables for the withdrawal “I exchanged 20 euros at the rate of 2.11”. For a floating point value, use double .
... decision<-!
import std.stdio;
void main ()
{
int amount = 20;
double rate = 2.11;
writeln ("I traded", amount,
"euro at the rate", rate);
}
->
import std. stdio ;
void main ( )
{
int amount = 20 ;
double rate = 2.11 ;
writeln ( "I traded" , amount ,
"euro at the rate" , rate ) ;
}
Standard input and output streams
Up to this point, the entire printed output of our programs appeared in
the console window . Although it is in fact often used by many programs, in fact, characters are output to
standard output streams .
Standard output is based on characters; all that is printed is first converted into a character representation and then sequentially sent to the output as characters. For example, the integer value 100, which we derived in the last chapter, is not sent to the output as the value 100, but as the three characters
1 ,
0 and
0 .
Similarly, what we usually perceive as a
keyboard is actually a
standard program
input stream , and it is also based on characters. Information always comes in as characters for conversion to data. For example, the integer value 42 actually comes in via standard input as characters
4 and
2 .
These conversions are done automatically.
This concept of consecutive characters is called a
character stream . Since the standard input stream and the standard output stream fit this description, they are character streams.
The names of the standard input and output streams in D are
stdin and
stdout, respectively.
Operations on these streams usually require the name of the stream, the point and the name of the operation; for example
stream.operation () . Since
stdin and
stdout are used very often, by convention, standard operations on them can be invoked without the need to specify a name and a period, for example
operation () .
The writeln we used in the previous chapters is actually an abbreviation of
stdout.writeln . Also
write is short for
stdout.write . Accordingly, the “Hello World” program can be written as follows:
import std. stdio ;
void main ( )
{
stdout. writeln ( "Hello world!" ) ;
}
Exercises
- Make sure that stdout.write works the same as write .
... decisionimport std. stdio ;
void main ( )
{
stdout. writeln ( 1 , "," , 2 ) ;
}
Read from standard input stream
Any data that has been read by the program must first be saved to a variable. For example, a program that reads the number of students from the standard input stream should save this information into a variable. The type of this particular variable can be int.
As we saw in the previous chapter, there is no need to specify
stdout when printing information, as it is supposed to. Further, what is output is specified as an argument. Therefore,
write (studentCount) is enough to print the value of
studentCount . Summarize:
: stdout : write : studentCount : ,
Reverse write operations - readf; it reads from the standard input stream. The letter “f” in the name is taken from “formatted”, since what this function reads must always be in a specific format.
Also in the last chapter, we learned that the standard input stream is called
stdin .
In the case of reading one piece of the puzzle is still missing: where to save the data. Let's sum up:
: stdin : readf : : ?
The location of the place where the data is to be stored is indicated by the address of the variable. The variable address is the exact position in the computer's memory, where its value is stored.
In D, the '&' character printed before the name is an indication of the address of what this variable represents. For example, the
studentCount address is
& studentCount . Here,
& studentCount can be read as the "
studentCount address", and this is the missing piece that replaces the question mark above:
: stdin : readf : : studentCount
The character set & in front of the name means
taking the address of what that name represents. This concept is the basis of references and pointers, which we will see in the following chapters.
I will postpone the explanation of one particular use of
readf ; for now,
let's accept the rule that the first argument of
readf should be the string "% s":
readf("%s", &studentCount)
Note: As I explain below, in most cases, the line must also contain a space: "% s"."% s" indicates that the data should be automatically converted in a way that matches the type of the variable. For example, when the characters '4' and '2' are read into a variable of type
int , they must be converted to an integer value 42.
The program below asks the user to enter the number of students. You must press the Enter key after the input is complete:
import std. stdio ;
void main ( )
{
write ( "How many students are present?" ) ;
/ *
* Declaring a variable to be used for
* storing information that is read from the input stream
* /
int studentCount ;
// Write input to this variable
readf ( "% s" , & studentCount ) ;
writeln ( "Understood: Present," studentCount , "students." ) ;
}
Skipping whitespace characters
Even the Enter key, which we press after entering data, is saved as a special code and placed in the
stdin stream. This helps programs detect whether information has been entered in one or more lines.
Although this is sometimes useful, such specific codes are in most cases not important for the program and should be removed from the input. Otherwise, they
block the input and do not allow to read other data.
To demonstrate the problem, let's also read the number of teachers from the input stream:
import std. stdio ;
void main ( )
{
write ( "How many students are present?" ) ;
int studentCount ;
readf ( "% s" , & studentCount ) ;
write ( "How many teachers are there?" ) ;
int teacherCount ;
readf ( "% s" , & teacherCount ) ;
writeln ( "Understood: Present," studentCount , "students" ,
"and" , teacherCount , "teachers." ) ;
}
Unfortunately, now the program is stuck while reading the second
int :
? 100 ? 20 <-
Although the user entered the number of teachers equal to 20, special codes that represent the Enter key while reading the previous value of 100 are still in the input stream and block it. Characters that are stored in the input stream are similar to the following:
100[EnterCode]20[EnterCode]
The first [EnterCode] character blocks input.
The solution to this problem is to add a space before% s to indicate that the Enter key code, which can be met before reading the number of teachers, is not important: "% s". Spaces in the format string are used to read and ignore zero or more invisible characters that may precede the input. Such characters include: the space character itself, codes that represent the Enter key, the Tab key character, and others, called
whitespace characters .
In general, you can use "% s" for any data that is read from the input stream. The program above works as expected with the following changes:
// ...
readf ( "% s" , & studentCount ) ;
// ...
readf ( "% s" , & teacherCount ) ;
// ...
Conclusion:
? 100 ? 20 : 100 20 .
Additional Information
- Lines that begin with // indicate single-line comments. To write a multi-line comment, enclose the lines in the / * and * / labels.
To comment out other comments, use / + and + /:
/ +
// Single line comment
/ *
Comment that takes
few lines
* /
Comment block that includes other comments
+ /
- Most spaces in the source code do not matter. It is a good practice to write long expressions on several lines or add extra spaces to make the code more readable. However, as long as the syntax rules of the language are observed, programs can be written without any additional spaces:
import std. stdio ; void main ( ) { writeln ( "Hard to read!" ) ; }
It is difficult to read the code in which there are as many spaces as in this.
Exercises
- Enter non-numeric characters when the program is expecting an integer value and observe how the program works incorrectly.
... decisionWhen characters cannot be converted to the desired type, stdin is rendered unusable . For example, typing “abc” when an int is expected will make stdin unusable .