JJJJJJ
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Data Types ## 1 ```c #include <stdio.h> int main() { unsigned int i=10; while(i-- >= 0) printf("%u ",i); return 0; } ``` :::spoiler Answer Output:  In C, unsigned integer overflow is defined to wrap around, while signed integer overflow causes undefined behavior 9 8 7 6 5 4 3 2 1 0 4294967295 4294967294 …… (on a machine where int is 4 bytes long) 9 8 7 6 5 4 3 2 1 0 65535 65534 …. (on a machine where int is 2 bytes long) As a side note, if i was `signed int`, the while loop would have been terminated after printing the **highest positive value**. > Output: 9 8 7 6 5 4 3 2 1 0 4294967295 假設只有 4 個 bits: | number | binary form | | -------- | -------- | | 2 | 0010 | | 1 | 0001 | | 0 | 0000 | | -1 | 1111 | 減一就是加上負一,可看到 `0 + (-1)` 的 binary form 會是 `1111`,evaluate to a `unsigned int` 就會是 `15`,剛好是 `4` bit 能表示的最大數字。 ::: ## 2 ```c #include <stdbool.h> #include <stdio.h> bool is_one(int i) { return i == 1; } int main() { struct { signed int a : 1; } obj = { .a = 1 }; puts(is_one(obj.a) ? "one" : "not one"); return 0; } ``` :::spoiler Answer 在 struct {int a : 1; } obj = {.a = 1 }; 的地方,原本 int 這個資料型態需要 4 bytes 的空間,即 32 個位元,我們透過 bit field 指定只用其中一個 bit 來存放數值。 但因 a 是 signed integer,所以 1 個 1 bit 表示為 signed interger 是 -1。若改成 unsigned interger 就會是 1,輸出就是會 "one"。 如果題目的 int 並沒有說是 signed 或 unsigned ,那麼 bit-field 宣告之後究竟該是 signed / unsigned 是由編譯器所決定的。 在此例中,`obj.a` 會是 `-1`。 ::: ## 3 ```c int main() { signed char i=0; for(; i >= 0; i++); printf("%d\n", i); getchar(); return 0; } ``` :::spoiler Answer Output: -128 Explanation: 但這其實是 undefined behavior (signed interger overflow)。 - [資料類型範圍](https://learn.microsoft.com/zh-tw/cpp/cpp/data-type-ranges?view=msvc-170) - signed char -> 1 byte, from -128 to 127 ::: ## 4 ```clike void foo(void) { unsigned int a = 6; int b = -20; (a+b > 6) ? puts("> 6") : puts("<= 6"); } ``` :::spoiler Answer Output: > 6 Explaination: > From the C99 standard, section 6.3.1.8 ("Usual arithmetic conversions"): > > if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. 當表達式中存在有符號類型和無符號類型時所有的操作數都自動轉換為無符號類型。因此-20變成了一個非常大的正整數,所以該表達式計算出的結果大於6。 ::: ## 5 What Is The Output Of this program? ```clike #include <stdio.h> int main() { unsigned int a = 0xffff; unsigned int k = ~a; printf("%d %d\n", a, k); return 0; } ``` :::spoiler Answer Output: 65535 -65536 Explaination: a 為 `0x0000ffff`,因此 k 為 `0xffff0000`。而 `%d` 代表要印出 signed int。`%u` 才是印出 unsigned int。 see [printf specifiers](https://cplusplus.com/reference/cstdio/printf/) ::: ## 6 What Is The Output Of this program? ```clike #include <stdio.h> int main() { unsigned int a = -1; unsigned int b = 4; printf("%d\n", a << b); return 0; } ``` :::spoiler Answer Output: -16 Explaination: a in hex: `0xffffffff`, thus b in hex: `0xfffffff0`, which is -16。 不想計算那麼多位可以直接用 binary `111111` left shift 4 bit 來計算:`110000`,值為 -32 + 16 = -16。 ::: ## 7 What Is The Output Of this program? ```clike #include <stdio.h> int main() { unsigned int m = 32; printf("%d %d", m >> 1, ~m); return 0; } ``` :::spoiler Answer Output: 16, -33 Explaination: right shift a unsigned int are well defined ! - [Can you control what a bitwise right shift will fill in C?](https://stackoverflow.com/questions/8422424/can-you-control-what-a-bitwise-right-shift-will-fill-in-c/8422852#8422852) > Here's what the C99 standard says (section 6.5.7): > > The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined. > > The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. > > The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined. ::: ## 8 What Is The Output Of this program? ```clike #include <stdio.h> int main() { float a = 12.5; printf("%d\n", a); printf("%d\n", (int)a); printf("%d\n", *(int *)&a); return 0; } ``` :::spoiler Answer 參考答案: 該項程序輸出如下所示, 0 (-749071256 (x86-64 clang 17.0.1), 1027694856 (x86-64 gcc 13.2)) 12 1095237632 Explaination: 12.5f 的二進制表示法 (sign, exponent, mantissa): | sign | exponent | mantissa | | -------- | -------- | -------- | | 0 | 10000010 | 10010000000000000000000 | 先把 12.5 轉二進位:1100.1,平移三位後:1.1001,所以 exponent 會是 3 + 127 = 130,130 二進位表示為 10000010。mantissa 就是平移之後的結果補滿零。 因此 12.5f in binary = 01000001010010000000000000000000。 - [IEEE-754 Floating Point Converter](https://www.h-schmidt.net/FloatConverter/IEEE754.html) 十六進制是:0x41480000,十進制是:1095237632。 第二和第三行的 output 比較簡單就可以判斷出來,`(int) a` 就是 cast a float to int,直接去掉小數點。`*(int *)&a` 是 dereference a interger pointer which points to this floating point,對於這 32 個 bit 而言,會用 interger 的觀點去處理,而 01000001010010000000000000000000 對於 int 來說,值就是 1095237632。 而對於第一個,為什麼會輸出 0? 我們需要瞭解一下 float 和 double 的記憶體佈局,如下: float: 1位符號位(s)、8位指數(e),23位尾數(m,共32位) double: 1位符號位(s)、11位指數(e),52位尾數(m,共64位) 然後,我們還需要瞭解一下 printf 由於類型不匹配,所以,會把 float 直接轉成 double([What happens to a float variable when %d is used in a printf?](https://stackoverflow.com/questions/7480097/what-happens-to-a-float-variable-when-d-is-used-in-a-printf)),注意,12.5 的 float 和 double 的記憶體二進制完全不一樣。別忘了在x86晶片下使用是的反位元組序,高位位元組和低位字位要反過來。所以: float版:0x41480000 (在記憶體中是:00 00 48 41) double版:0x4029000000000000 (在記憶體中是:00 00 00 00 00 00 29 40) 而我們的%d要求是一個4位元組的int,對於double的記憶體佈局,我們可以看到前四個位元組是00,所以輸出自然是0了。 這個示例向我們說明printf並不是類型安全的,這就是為什麼C++要引如cout的原因了。 :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully