Home C++_Lecture04(From namespace)
Post
Cancel

C++_Lecture04(From namespace)

Namespaces

Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. But this long definition is too hard to understand the full meaning so I prepared some examples to explain what is namespace.

1
2
3
4
5
6
7
8
9
10
11
#include "iostream"
using namespace std;

namespace nice_seoul {
int a;//namespace a
}
int a = 5;//global a
int main() {
  nice_seoul::a = 7;//namespace
  cout << a;
}

Look at this set of code. This code explains why we use namespace. As you can see in the code there are two kinds of “a” variable. One is namespace a variable and one is just global variable a. If we print out a in the main function the result you will see is 5. The purpose of the name space is to give no confusion while writing code. So professor told us that he doesn’t like to use using namespace. Because this doesn’t fit the purpose of the namespace.


Break

Before I start next chapter. I prepared a simple question I had last time studying C++.

1
2
3
4
5
6
7
8
# include "iostream"
using namespace std;

int main(void){
	int i = 10
	cout<<i+++i<<endl;
  cout<<i<<endl;
}

What would the first line print out. This issue was the biggest controversy at the time of the last study. he results came out differently depending on which program you turn on the shipple, and I’m going to write down the results of asking the professor about it! First, all of the program printed out the next line as 11. But some of the program printed out first line as 20 while others printed out as 21. To be simple if it depends on the difference of compiler one of them is wrong and don’t have to study those.


Functions

Below code shows how the function works. First we should look at function assign. Simply put, it can be thought of as a function that puts the number 6 in the address value of a. So when this assign function is used below it should have changed the value of y to 6 but instead y value is still 8. Why would this happen. To understand the progress we should first learn about the function’s calling method.

Call by value

In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method. In call by value method, we can not modify the value of the actual parameter by the formal parameter. In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter. The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition. This is the simple example showing the result how call-by-value works in the code.

한글을 좋아하는 여러분을 위해 간단하게 한글 요약도 정리했다. 간단한 설명을 위해 예시를 준비하였다. 한 아파트내에 많은 집들이 위치하고 있고, 경비아저씨가 각 집들을 찾아가면 값을 받을 수 있다. Call-by-value라는 방식의 함수 호출은 change(x)가 실행될 때, x라는 집에 살고 있는 값을 경비아저씨가 확인하고 x라는 집은 아니지만 값은 완전히 동일한 집을 하나 만들고, 그 집의 값을 가지고 함수 내부에서 활용하는 것이다. 그렇다 보니 원래 x라는 집에 있던 값은 변하지 않고 x라는 값을 똑같이 옮겨간 그 다른 집의 값만 바뀌는 것이다. 하나 궁금한 점은 이 복사해간 집의 주소에는 함수가 끝난 이후에 값을 해제해줄까 아니면 유지할까? 지금 컴퓨터 컴파일러가 아파서 시도해보진 못하지만 좀 설정을 완료하고 나면 시도해 보려고 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>  
void change(int num) {    
    printf("Before adding value inside function num=%d \n",num);    
    num=num+100;    
    printf("After adding value inside function num=%d \n", num);    
}    
int main() {    
    int x=100;    
    printf("Before function call x=%d \n", x);//Print outs 100
    change(x);//passing value in function -> 100 and 200    
    printf("After function call x=%d \n", x);//Print outs 100    
return 0;  


Call by reference

In call by reference, the address of the variable is passed into the function call as the actual parameter. The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed. In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.This is the simple example showing the result how call-by-reference works in the code.

간단하게 설명하기 위해 이 부분도 한글을 준비했다. 아까의 예시에서는 경비아저씨가 값을 확인해서 전달했다면 지금은 경비아저씨가 몇동 몇호인지를 전달해준다고 생각하면 간단하다. 그렇다보니 몇동 몇호에 직접적으로 값의 변화를 일으킬 수 있고, 이 부분이 함수 호출 후 활용하는 과정에서 큰 차이점 두 가지다.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>  
void change(int *num) {    
    printf("Before adding value inside function num=%d \n",*num);    
    (*num) += 100;    
    printf("After adding value inside function num=%d \n", *num);    
}      
int main() {    
    int x=100;    
    printf("Before function call x=%d \n", x);    
    change(&x);//passing reference in function    
    printf("After function call x=%d \n", x);    
return 0;  
}    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "iostream"
using namespace std;
//call by value and call by reference
void assign(int a){
  a = 6;
}//need to explain how the function works!

int max(int a, int b){// formal arguments/parameter
  int u = 9;//define variables in function = local variable
  if (a > b) return a;
  else return b;
}
int k = 100; // Global variables
int main() {
  int x = 6, y = 8;
  cin>>x>>y;
  cout<<max(x,y)<<endl;//actual arguments/parameter
  int z = max(x,y);
  assign(y);
  cout<<y<<endl;
}

Below code is an example that will help us understand how the function works. If we run the code the error will occur. When running funcA funcB is not yet declared so computer won’t find the funcB. This will make the code stop. But if we add the prototype of funcB right below the using namespace line this will work well. So only thing we should do to make this code work is to put int funcB(int) above the funcA as a prototype declaration.

#include "iostream"
using namespace std;

// What is the visibility of max function
// Problem occurs Func A -> Func B && Func B -> Func A
// To solve this type we should use proto type
int funcA(int a){
  if (a > 0) 
    funcB(a - 1);
  else 
    return 1;
}

int funcB(int a){
  if (a>0) funcA(a - 1);
  else return 2;
}

int main(){
  cout<< funcA(10)<<endl;
}

Recursion

Recursion means “defining a problem in terms of itself”. This can be a very powerful tool in writing algorithms. Below is one of the most famous recursion question fibonacci. Inside the fibonacci function it returns fibonacci function itself to solve the question. This kind of method is called recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include "iostream"
using namespace std;

int fibonacci(int n){
	if (n == 1 or n == 2){
    return 1;
  }
  else if (n == 0){
    return 0;
  }
  else:
  	return fibonacci(n - 1) + fibonacci(n - 2)
}

Below is the example our professor has showed. This code is simply solving the famous Tower of Hanoi. If you are interested in solving some algorithm problems. You can use BOJ web site to test personal algorithm solving skills. No.1914 is the same question. If you want to try I recommend it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "iostream"
using namespace std;

void tower(int n, char source, char dest, char aux, int *c){
  if (n > 1){
    tower(n - 1, source, aux, dest);
    *c+=1
    //cout<<"Move Disk from "<<source<<"to "<<dest<<"\n";
    tower(n - 1, aux, dest, source, &c);
  }
  else{
    *c += 1
    //cout<<"Move Disk from"<<source<<"to"<<dest<<"\n";
  }
}

int main(){
  int c = 0
  tower(3, "A", "C", "B", &c);
  cout<<c<<endl;
}

Static and Extern storage

Declaring a local variable as static means it will remember it’s last value.(Local variables are auto by default.) Below is the simple example. The output for two fun() will be 9 10. Which means int l is saved as 9 eventhough the function is ended.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "iostream"
using namespace std;

int j; // declaration
int fun(){
  static int l = 8;//Works like a global variable
  l += 1;
  return l;
}
int main(){
  cout<<j<<endl;
  cout<<fun()<<endl;
  cout<<fun()<<endl;
}
This post is licensed under CC BY 4.0 by the author.

Operations on one matrix - part 2

First TIL