C++ Basic - 01 Function

# WHY: Why shouldn’t we learn from "Hello, world" first?

I believe many people are confused about the reason we start from function instead of popular "Hello, world". It is because "Hello, world" program is too difficult to beginner.

Some people might still be confused with difficult, then let’s have a review of the program first:

#include <cstdio>
int main() {
    printf("Hello, world!\n");
    return 0;
}

or

#include <iostream>
using namespace std;
int main() {
    cout << "Hello, world!" << endl;
    return 0;
}

At the first sight of these, you possibly confused about what include is, what is included in namespace, why we should add int main(), etc. But your professor would possibly reply that don’t ask, remember first?

As a science subject that is focusing on logic, I am opposed with such an unlogical way to study. What is more, "Hello, world" program is used for testing compiler instead of learning. Thus, I prefer to start with an easier program with less confusing things:

int f(int x) {
    return x + 1;
}

To be more accurate, this is not a program but a function that is supposed to be the beginning for beginner.

# WHAT

# What is function?

Ref. Wikipedia: In mathematics, a function from a set $X$ to a set $Y$ assigns to each element of $X$ exactly one element of $Y$.

Too abstract? Just understand that Function is a “machine” containing some functions. E.g. $f(x) = x + 1$ machine $f(x)$ contains a function that could help to add 1 to input.

Then, you might find that all math or cs questions could be turned into functions with different complexity like $f(g(x) + h(y) \cdot u(z))$. And if we turn this into a language that computer could understand, it is a program.

Now, you might understand why should we start from function. Function, is the most basic logic under program. Or, all programs are consisted by functions.

# What is the components of function?

Let’s have a review of the previous function: int f(int x){return x + 1;}, which equals to $f(x) = x + 1$ in mathematics. It’s time to fully understand this function:

int f(int x) {
    return x + 1;
}
  • int: tell computer (declare) that the output ($f(x)$) and input ($x$) are integers. We have to tell computer every variable’s type so that the computer could store it properly.
  • (int x): input value. In the following program we could call this function by just using f(1), f(2)
  • return: tell computer that the function next is to output the value followed by return and then function would be terminated.
  • ;: separate different commends in the function.
  • { }: to “pack” the function.

You might have an overview of function now, then let’s move to a more complex function:

int function(int a) {
    int bestNum;
    bestNum = 7;
    a = bestNum;
    a = 2 * a;
    bestNum = a;
    return bestNum;
}

Line 1: At this time, we declare two things, function() and a, as integers. You might find that we do not use f() this time, we use function() instead. Right, and function is better than f because while reading code, people could easier to get programmers’ points.

Line 2 & 3: int bestNum = 7 in short (and preferred). As I have mentioned above, bestNum is better than bn or just b because we could understand it better. In this point, we declare bestNum is an integer and assign 7 to bestNum. Let me describe two things: how do the name of bestNum come and what is assign:

  • camelCase: while writing a variable, we cannot divide the terms into separated words for computer cannot recognize it correctly like we cannot write camelCase to camel case. In this case, we have several ways to name this like camel_case, camel-case, CamelCase. But camelCase is one of the wide-use approach for its high efficiency. And the name of the naming method is Camel Case. And num is number in short. There is also some abbr like ans refer to answer, cnt refer to counter, etc.
  • =: = does not mean equal, but assign. Equal is a kind of judgement (We will learn it later about ==), but Assign is a kind of calculation. To fully understand this, let’s look deeper into computer memory. When we declare variables, the computer will give every variable some memory for store number like computer will give int 32 bits (4 bytes) to store and give long long int 64 bits to store which means long long int is able to store larger integer. Every type use only 0 and 1 to store number thus when we assign, many 0 and 1 change to store the number when we assign to the variable.

Line 4: We assign the number store in bestNum to a. And remember, a is not a preferred name. When we write program, please make it more specific.

Line 5: We assign the number that store in a and then times two to a. We calculate the number at the right of = first and then assign the number we calculated to the left variable.

Line 6: We assign the number store in a to bestNum

Line 7: The overall function function() returns an integer number bestNum.

In a nutshell, the function of function() is that first assigning $7$ to bestNum that we declare as an integer, then assign bestNum to a, then assign the number that a times $2$ to a, then assign a back to bestNum, finally returns bestNum.

You might find that there is no point to input a for it will be ‘refreshed’ or assigned with another number bestNum in line 4. So we could rewrite line 1: int function() {

If you could get the points in the nutshell, then congratulation that you stepped in c++ now. But you might still be confused about although there is no CE (Compile-time Error) but RE (Runtime Error). Which the function that the overall program start with?

# The main function of a program - main() function

int f(int x, int y) {
    return x + y;
}
int main() {
    int a = 1;
    int b = 1;
    int c = f(a, b);
    return 0;
}

This is a program without input and output (We will take about how to input and output in terminal next course). Let’s have an analysis of this function:

  • The program begins from main(), but why do we write from f()? It is because every function is supposed to be known before usage (When solving math problems, we are also supposed to clarify the function of every function before usage).
  • return 0 of the main() does not mean that the whole program would return 0 after running - 0 in C++ means that the whole program runs without problem.
  • You might notice that in this time, f() have two parameters, it is valid. (It is also valid in mathematics)

If you could get the point, let’s forward to a more .complicated program:

int h(int i) {
    return i;
}
int f(int i) {
    return h(i);
}
int main() {
    int i = ...;
    f(i);
    return 0;
}

Could you tell the sequence of this program?

main -> f -> h (return) -> f -> main

It is a stack structure, which we put main in the bottom first, then f, then h. When we want to return, we also have to pick from the top first: h, f then main.

The stack structure, which is defined as LIFO, Last In First Out, is widely use in algorithm, computer hardware, etc. We will gain a deeper sight of this in the following courses.

# HOW: How to write a Program?

# Begin with main() is a good habit

From the knowledge we have learned above, every program contains a main() function.

int main() {
    *sentence*;
    return 0;
}

We know that the return value of main() is not important. But why do we declare main as integer instead of other type like boolean bool?

At the beginning, I hope to improve the answer searching ability for everyone.

  1. For the question why do we declare main function as int in c++?, we abstract the keywords: why declare(question) main(target 1) int(target 2) c++(field)
  2. Choose a platform for searching: Google, DuckDuckGo, Stack Overflow, and other forums.
  3. Type in the keywords and search.

After several searching, you might find the answer: The short answer, is because the C++ standard requires main() to return int . As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished.

In short, this is a regulation when C++ was created. When program return 0 everything goes well.

I use this case to emphasize that the purpose of my blog is not finding answer but getting better understanding and logic for specific knowledge. I hope everyone could follow How To Ask Questions The Smart Way before asking questions.

The first thing to understand is that hackers actually like hard problems and good, thought-provoking questions about them. If we didn’t, we wouldn’t be here. If you give us an interesting question to chew on we’ll be grateful to you; good questions are a stimulus and a gift. Good questions help us develop our understanding, and often reveal problems we might not have noticed or thought about otherwise. Among hackers, “Good question!” is a strong and sincere compliment.

Now, we know how to create a structure of a program, then what about calculation?

# Arithmetic

  • Basic + - * / could be use directly. E.g. int a = 5 - 3;, float b = 3 / 6 (float is a type could store float number). But notice that / still cannot divide with 0. Although there is no CE, but RE will happen while running the program.
  • = We have clarified that = is not equal but assign as an arithmetic.
  • Mod calculation: %. E.g. int a = 8 % 3; // a equals 2 (// is a comment sign. The content after // will not be compiled and run. /*content*/ is similar to //, but you can comment for several lines.)

# Practice

As the first practice, I will declare that how to use practice to improve ourselves.

Practice has three levels: KNOW, UNDERSTAND, MASTER

  • KNOW focuses on the content itself of the posts, which is necessary for basis. Figuring out KNOW means that you fully read the post in this course. If you cannot solve KNOW, please read the post carefully again without distraction.
  • UNDERSTAND makes some modification with content itself and parameters, which is necessary for next learning. Figuring out UNDERSTAND means that you gain your own understanding while reading the post. If you cannot solve UNDERSTAND, please conclude the post and find out what you miss in this course, you could ask search engine for help as well.
  • MASTER explores deeper into knowledge and content, which is necessary for mastering C++ and next learning for algorithm. Figuring out MASTER means that you get every point of the post and build your would logical system of learning C++. If you cannot solve MASTER, you could read the answer directly and then understand how the answer works. After that, re-answer the question again.

# KNOW

int f(int x) {
    return x * 2;
}
int main() {
    int a = 1;
    a = f(a);
    return 0;
}

Find the value of a.


a equals 2.

# UNDERSTAND

int h(int x){
    return 1;
}
int g(int x){
    return h(x);
}
int f(int x){
    return g(h(x));
}
int main(){
    int a = 7;
    a = f(a);
    return 0;
}

Find the sequence of the functions and value of a


  1. main -> f -> h(brackets have a higher privilege for calculation) -> g -> h(return) -> g -> f -> main

  2. a equals 1.

# MASTER

Write a function switch(int a, int b) that could switch the value stored in a and b, then returns a.


int switch(int a, int b){
    int c = a;
    a = b;
    b = c;
    return a;
}
Built with Hugo
Theme Stack designed by Jimmy