# 2016q1 homework 4(A)
## C 語言程式設計
投影片:[](http://www.slideshare.net/olvemaudal/deep-c)http://www.slideshare.net/olvemaudal/deep-c
**DEEP C 投影片重點整理:**
* 只列出一些我之前都不太明白或不懂的東西
```clike=
int main()
{
int a = 42;
printf("%d\n",a);
}
```
上述程式碼C++ compiler會拒絕編譯,因爲對C++來說每個function都需要explicit declaration。而對C而言,C會先建立一個implicit declaration的pinrtf(),然後當程式linked到standard library時會找到pinrtf的定義,才能使用printf()。所以C是可以對上面的code進行編譯跟執行,但會得到警告訊息。
---
```clike=
#include <stdio.h>
void foo(void) {
static int a;
int b;
++a;++b;
printf("%d %d\n",a,b);
}
int main(void) {
foo();foo();foo();
}
```
Static "a" 變數會在宣告的時候初始化成0,而區域變數 "b"則不會。這是因爲C很重視程式的執行速度效率。初始化一個全域變數 Is a one time cost that happens at start up,而變數"b"則會增加function calls。
在這裏有一個地方要值得注意:
* 1\. void foo(void)
* 2\. void foo()
這兩個的差別:
* 第一個表示不接受任何參數,意思就是當你呼叫 foo(1,2,3) 會編譯錯誤
* 第二個可以接受任何參數,當你呼叫foo(1,2,3),對C compiler來說還是會成功讓你編譯
* 我測試了一下,對C++ compiler來說,兩個都不能接受任何參數,foo(1)會編譯錯誤錯誤
---
```clike=
#include <stdio.h>
int b(void) { puts("3"); return 3;}
int c(void) { puts("4"); return 4;}
int main(void)
{
int a = b() + c();
printf("%d\n",a);
}
```
The evaluation order of most expressions in C and C++ are unspecified, the compiler can choose to evaluate them in the order that is most optimal for the target platform. So this code will either print 3,4,7 or 4,3,7, depending on the compiler.
---
```clike=
#include <stdio.h>
struct X{ int a; char b; int c;};
int main()
{
printf("%zu\n",sizeof(int));
printf("%zu\n",sizeof(char));
printf("%zu\n",sizeof(struct X));
}
```
上面的結果會是4,1,12。爲了增加效能,Compiler 會幫我們做優化,也就是記憶體對齊,因此會給struct多準備一些記憶體。
由於不太明白這裏,所以我就做了一點測試:
```clike=
#include <stdio.h>
struct W{char a;};
struct X{int a; char b; char c;};
struct Y{char a; int b; char c;};
struct Z{char a; char b; int c;};
int main()
{
printf("%zu\n",sizeof(struct W)); //Output 1
printf("%zu\n",sizeof(struct X)); //Output 8
printf("%zu\n",sizeof(struct Y)); //Output 12
printf("%zu\n",sizeof(struct Z)); //Output 8
}
```
不太明白的是爲什麼struct Y的結果會是12,而struct X,Z的則是8,結構是一樣的,只是宣告的順序不同。再來上網看了一些資料說會是4或8的倍數,也有2次方的,可是結構struct W卻只有1?
## 系統程式概念
* [From Source to Binary](http://www.slideshare.net/jserv/how-a-compiler-works-gnu-toolchain)
* [Hello World!](http://wen00072-blog.logdown.com/posts/190025-hello-world)
* [Something Behind Hello World](http://www.slideshare.net/jserv/helloworld-internals)