refactor(topics): 멀티 에이전트용 지식 재편 — _Common(공통 기본기) + Domain_* 구조
에이전트 8종(대화형/프로그래머 C·S/디자이너/설계자/기획자/QA/PD/PM)에게 [공통 기본 능력 + 롤별 Specialty] 2층으로 지식을 주입하기 위한 재분류. 문서 내용·포맷은 무수정, 폴더 이동만 (6,372개 문서 수 보존 확인). - Topic_Programming → Domain_Programming (내부 구조 보존) - Topic_Graphic → Domain_Design - Topic_Business → Domain_Product - Topic_General → Domain_General - _Common 신설: Math(구 Topic_Math_Specialty), Reasoning(구 General/From_Thinking & Reasoning), Reasoning_Creativity(구 General/From_창의성), Communication(Poetic_Blog_Writing + From_writing) - 타 도메인의 From_* 폴더는 유지 (출처 표기일 뿐, 이미 도메인에 맞게 분류된 문서) - 빈 폴더 정리 (memory/procedures) - 에이전트→폴더 매핑은 workspace의 .astra/agent-knowledge-map.json (9개 에이전트) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,191 @@
|
||||
---
|
||||
id: c-tutorial-index
|
||||
title: "C Tutorial"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["C Tutorial", "C MOC", "Topic_C index", "C 언어 목차"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.90
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "moc", "index"]
|
||||
raw_sources: ["https://www.w3schools.com/c/index.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Tutorial]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Map of Content (MOC) for the W3Schools C Tutorial — the root that links every core C knowledge page in this topic folder. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- This folder (`Topic_C`) wikifies the C programming language tutorial, one knowledge page per document, in P-Reinforce v3.1 format — same convention as `Topic_SQL` / `Topic_Python` / `Topic_Java` / `Topic_PHP` / `Topic_W3CSS` / `Topic_HTML` / `Topic_CSS` / `Topic_JavaScript`. [S1]
|
||||
- **Scope**: tutorial + "Learning by examples" pages only. **Excluded**: `c_challenges_*` (18 code-challenge pages), `c_compiler`/`c_examples`/`c_exercises`/`c_practice`/`c_projects`/`c_quiz`/`c_exam`/`c_interview_questions`/`c_study_plan`/`c_syllabus`/`c_real_life_examples` (meta/index pages), `c_ref_*` (7 reference-dump pages: ctype, keywords, math, reference, stdio, stdlib, string, time). [S1]
|
||||
- **97 of 97 planned docs complete — C category done.**
|
||||
- Every page roots its Knowledge Graph back to this `[[C Tutorial]]` node.
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
|
||||
### Basics
|
||||
- [[C Intro]] ✅
|
||||
- [[C Get Started]] ✅
|
||||
- [[C Syntax]] ✅
|
||||
- [[C Statements]] ✅
|
||||
- [[C Output]] ✅
|
||||
- [[C Comments]] ✅
|
||||
- [[C Organize Code]] ✅
|
||||
|
||||
### Variables
|
||||
- [[C Variables]] ✅
|
||||
- [[C Variables Names]] ✅
|
||||
- [[C Variables Change]] ✅
|
||||
- [[C Variables Multiple]] ✅
|
||||
- [[C Variables Format]] ✅
|
||||
- [[C Variables RealLife]] ✅
|
||||
|
||||
### Data Types
|
||||
- [[C Data Types]] ✅
|
||||
- [[C Data Types Numbers]] ✅
|
||||
- [[C Data Types Characters]] ✅
|
||||
- [[C Data Types Dec]] ✅
|
||||
- [[C Data Types Extended]] ✅
|
||||
- [[C Data Types Sizeof]] ✅
|
||||
- [[C Data Types RealLife]] ✅
|
||||
|
||||
### Constants & Storage
|
||||
- [[C Constants]] ✅
|
||||
- [[C Storage Classes]] ✅
|
||||
- [[C Fixed Width Ints]] ✅
|
||||
|
||||
### Operators
|
||||
- [[C Operators]] ✅
|
||||
- [[C Operators Arithmetic]] ✅
|
||||
- [[C Operators Assignment]] ✅
|
||||
- [[C Operators Comparison]] ✅
|
||||
- [[C Operators Logical]] ✅
|
||||
- [[C Bitwise Operators]] ✅
|
||||
- [[C Operators Precedence]] ✅
|
||||
|
||||
### Strings
|
||||
- [[C Strings]] ✅
|
||||
- [[C Strings Esc]] ✅
|
||||
- [[C Strings Functions]] ✅
|
||||
|
||||
### Math & Random
|
||||
- [[C Math]] ✅
|
||||
- [[C Random Numbers]] ✅
|
||||
|
||||
### Booleans
|
||||
- [[C Booleans]] ✅
|
||||
- [[C Booleans RealLife]] ✅
|
||||
|
||||
### Conditions
|
||||
- [[C Conditions]] ✅
|
||||
- [[C Conditions Else]] ✅
|
||||
- [[C Conditions ElseIf]] ✅
|
||||
- [[C Conditions Short Hand]] ✅
|
||||
- [[C Conditions Logical]] ✅
|
||||
- [[C Conditions Nested]] ✅
|
||||
- [[C Conditions RealLife]] ✅
|
||||
|
||||
### Switch
|
||||
- [[C Switch]] ✅
|
||||
|
||||
### Loops
|
||||
- [[C While Loop]] ✅
|
||||
- [[C While Loop RealLife]] ✅
|
||||
- [[C Do While Loop]] ✅
|
||||
- [[C For Loop]] ✅
|
||||
- [[C For Loop Nested]] ✅
|
||||
- [[C For Loop RealLife]] ✅
|
||||
- [[C Break Continue]] ✅
|
||||
|
||||
### Arrays
|
||||
- [[C Arrays]] ✅
|
||||
- [[C Arrays Size]] ✅
|
||||
- [[C Arrays Loop]] ✅
|
||||
- [[C Arrays Multi]] ✅
|
||||
- [[C Arrays RealLife]] ✅
|
||||
|
||||
### Structs, Enums & Unions
|
||||
- [[C Structs]] ✅
|
||||
- [[C Structs Nested]] ✅
|
||||
- [[C Structs Padding]] ✅
|
||||
- [[C Structs Pointers]] ✅
|
||||
- [[C Enums]] ✅
|
||||
- [[C Unions]] ✅
|
||||
- [[C Typedef]] ✅
|
||||
|
||||
### Pointers & Memory
|
||||
- [[C Memory Address]] ✅
|
||||
- [[C Memory Access]] ✅
|
||||
- [[C Pointers]] ✅
|
||||
- [[C Pointers Arithmetic]] ✅
|
||||
- [[C Pointers Arrays]] ✅
|
||||
- [[C Pointer To Pointer]] ✅
|
||||
- [[C Memory Management]] ✅
|
||||
- [[C Memory Allocate]] ✅
|
||||
- [[C Memory Deallocate]] ✅
|
||||
- [[C Memory Reallocate]] ✅
|
||||
- [[C Memory Struct]] ✅
|
||||
- [[C Memory RealLife]] ✅
|
||||
|
||||
### Functions
|
||||
- [[C Functions]] ✅
|
||||
- [[C Functions Decl]] ✅
|
||||
- [[C Functions Parameters]] ✅
|
||||
- [[C Functions Recursion]] ✅
|
||||
- [[C Functions Pointers]] ✅
|
||||
- [[C Functions Callback]] ✅
|
||||
- [[C Functions Inline]] ✅
|
||||
|
||||
### Scope
|
||||
- [[C Scope]] ✅
|
||||
|
||||
### User Input & Date
|
||||
- [[C User Input]] ✅
|
||||
- [[C Date Time]] ✅
|
||||
|
||||
### Errors & Debugging
|
||||
- [[C Errors]] ✅
|
||||
- [[C Error Handling]] ✅
|
||||
- [[C Input Validation]] ✅
|
||||
- [[C Debugging]] ✅
|
||||
|
||||
### Files
|
||||
- [[C Files]] ✅
|
||||
- [[C Files Read]] ✅
|
||||
- [[C Files Write]] ✅
|
||||
|
||||
### Type Conversion & Macros
|
||||
- [[C Type Conversion]] ✅
|
||||
- [[C Macros]] ✅
|
||||
- [[C Null]] ✅
|
||||
- [[C Newline]] ✅
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
97 knowledge documents generated in this batch run, spanning Basics through Type Conversion & Macros.
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference)
|
||||
- **신뢰 점수:** 0.90
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[10_Wiki]]
|
||||
- **관련 개념:** [[C Intro]], [[PHP Tutorial]], [[Java Tutorial]], [[W3.CSS Tutorial]]
|
||||
- **참조 맥락:** SQL/Python/Java/PHP/W3.CSS에 이어 W3Schools 지식화 시리즈의 다음 카테고리 — 시스템 프로그래밍 언어 계열의 첫 항목.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Tutorial — https://www.w3schools.com/c/index.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Created C Tutorial MOC with scope decisions and full planned page list (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-arrays
|
||||
title: "C Arrays"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["array declaration", "fixed-size array", "C 배열"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "arrays"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_arrays.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Arrays]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Mixing types in an array literal (`int myArray[] = {25, 50, 75, 3.15, 5.99};`) doesn't always fail loudly — the source shows the float values `3.15`/`5.99` get silently TRUNCATED to `3`/`5` (since the array is typed `int`), and only "in some cases" does it produce an error, meaning the type-mismatch guard here is a silent-data-loss trap more often than a hard compile failure. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Array literal creation** — `type name[] = {val1, val2, ...};` creates and initializes an array in one step. [S1]
|
||||
- **Zero-based indexing** — `[0]` is the first element, `[1]` the second, and so on. [S1]
|
||||
- **Mutable elements** — any element can be reassigned by index after creation (`myNumbers[0] = 33;`). [S1]
|
||||
- **Size-first declaration** — `int myNumbers[4];` reserves space for 4 elements to be filled in later; the SIZE CANNOT CHANGE after creation. [S1]
|
||||
- **Same-type requirement** — all elements must share one data type; mismatched types get silently truncated/converted, not cleanly rejected. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Literal array creation and access: `int myNumbers[] = {25, 50, 75, 100}; printf("%d", myNumbers[0]); // 25`. [S1]
|
||||
- Modifying an element by index: `myNumbers[0] = 33; // Now outputs 33 instead of 25`. [S1]
|
||||
- Size-first, fill-later declaration: `int myNumbers[4]; myNumbers[0] = 25; myNumbers[1] = 50; myNumbers[2] = 75; myNumbers[3] = 100;`. [S1]
|
||||
- Type-mismatch truncation trap: `int myArray[] = {25, 50, 75, 3.15, 5.99};` — 3.15 and 5.99 silently become 3 and 5. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **타입이 섞이면 조용히 잘림**: int 배열에 float 값을 넣으면 항상 에러가 나는 게 아니라 대부분 소수점이 잘려나가는 형태로 조용히 처리되며, 일부 경우에만 에러가 발생한다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 크기를 먼저 선언하고 나중에 요소를 채우는 방식이 데이터가 순차적으로 들어올 때(예: 사용자 입력 반복) 실전에서 활용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Declaring an array's size first, then filling in elements later (C):
|
||||
```c
|
||||
int myNumbers[4];
|
||||
myNumbers[0] = 25;
|
||||
myNumbers[1] = 50;
|
||||
myNumbers[2] = 75;
|
||||
myNumbers[3] = 100;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Break Continue]], [[C Arrays Size]]
|
||||
- **참조 맥락:** 배열 섹션 첫 챕터 — 배열 크기(Arrays Size) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Arrays — https://www.w3schools.com/c/c_arrays.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-arrays-loop
|
||||
title: "C Array Loop"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["loop through array", "adaptive loop length", "C 배열 반복문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "arrays", "loops"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_arrays_loop.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Array Loop]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A hardcoded loop bound (`i < 4`) silently breaks the moment the array's contents change size — the source explicitly flags this as "not ideal, since it will only work for arrays of a specified size" — while replacing it with `sizeof(arr)/sizeof(arr[0])` makes the SAME loop automatically correct for an array of ANY length, turning a brittle magic number into a self-maintaining computation. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Hardcoded loop bound (fragile)** — `for (i = 0; i < 4; i++)` only works correctly for exactly a 4-element array; adding/removing elements breaks it silently. [S1]
|
||||
- **`sizeof` formula-driven bound (robust)** — `int length = sizeof(arr) / sizeof(arr[0]); for (i = 0; i < length; i++)` automatically adapts to the array's actual current size. [S1]
|
||||
- **Standing rule** — the chapter's own summary: "Always use the sizeof formula when looping through arrays." [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Fragile hardcoded-bound loop: `int myNumbers[] = {25, 50, 75, 100}; int i; for (i = 0; i < 4; i++) { printf("%d\n", myNumbers[i]); }`. [S1]
|
||||
- Robust size-adaptive loop: `int myNumbers[] = {25, 50, 75, 100}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); int i; for (i = 0; i < length; i++) { printf("%d\n", myNumbers[i]); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **하드코딩된 루프 경계의 취약성**: 배열 원소 개수가 바뀌면 i < 4 같은 고정된 조건이 더 이상 맞지 않게 된다는 점이 "이상적이지 않다"고 명시적으로 지적되며, sizeof 공식을 항상 쓰라는 규칙으로 이어짐. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — sizeof 기반 반복문이 이후 Arrays RealLife 챕터의 평균 계산·최솟값 찾기 예제에서 그대로 재사용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A loop that automatically adapts to any array size using the sizeof formula (C):
|
||||
```c
|
||||
int myNumbers[] = {25, 50, 75, 100};
|
||||
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
|
||||
int i;
|
||||
for (i = 0; i < length; i++) {
|
||||
printf("%d\n", myNumbers[i]);
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Arrays Size]], [[C Arrays Multi]], [[C Arrays RealLife]]
|
||||
- **참조 맥락:** 배열 반복문 — 다차원 배열(Arrays Multi) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Array Loop — https://www.w3schools.com/c/c_arrays_loop.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Array Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: c-arrays-multi
|
||||
title: "C Multidimensional Arrays"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["2D array", "matrix", "3D array", "C 다차원 배열"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "arrays", "multidimensional"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_arrays_multi.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Multidimensional Arrays]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A multidimensional array is defined as literally "an array of arrays," and this compounds directly into the looping requirement: an N-dimensional array needs exactly N nested loops to visit every element — a 2D array needs 2 nested loops (as shown), a 3D array would need 3 — meaning the loop-nesting depth isn't a stylistic choice but a direct structural consequence of how many dimensions the array has. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Multidimensional array** — "basically an array of arrays"; C supports any number of dimensions, with 2D being the most common. [S1]
|
||||
- **2D array (`type name[rows][cols]`)** — a matrix/table; first bracket = row count, second bracket = column count. [S1]
|
||||
- **Dual-index access** — `matrix[row][col]` addresses a specific cell; both indices are zero-based. [S1]
|
||||
- **One nested loop per dimension** — looping a 2D array fully requires 2 nested loops (outer for rows, inner for columns); a 3D array would require 3 nested loops. [S1]
|
||||
- **3D arrays (`type name[blocks][rows][cols]`)** — represent structures like multiple tables or game levels, each block itself being a 2D array. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Creating and accessing a 2D array: `int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; printf("%d", matrix[0][2]); // Outputs 2`. [S1]
|
||||
- Modifying a specific cell: `matrix[0][0] = 9; // Now outputs 9 instead of 1`. [S1]
|
||||
- Fully looping a 2D array with nested loops: `for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { printf("%d\n", matrix[i][j]); } }`. [S1]
|
||||
- Declaring a 3D array (2 blocks × 4 rows × 3 columns): `int example[2][4][3];`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **차원 수와 중첩 루프 개수의 직접 대응**: 2차원 배열은 중첩 루프 2개, 3차원 배열은 중첩 루프 3개가 필요하다는 구조적 대응 관계가 명시적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
2D 배열은 점수표, 게임판, 스프레드시트에, 3D 배열은 여러 테이블의 집합이나 게임의 여러 레벨 같은 복잡한 구조 표현에 적합하다고 원문에서 직접 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Fully iterating a 2D array requires one nested loop per dimension (C):
|
||||
```c
|
||||
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
|
||||
int i, j;
|
||||
for (i = 0; i < 2; i++) {
|
||||
for (j = 0; j < 3; j++) {
|
||||
printf("%d\n", matrix[i][j]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Arrays Loop]], [[C For Loop Nested]], [[C Arrays RealLife]]
|
||||
- **참조 맥락:** 다차원 배열 — 배열 실전 예제(Arrays RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Multidimensional Arrays — https://www.w3schools.com/c/c_arrays_multi.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Multidimensional Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-arrays-reallife
|
||||
title: "C Arrays - Real-Life Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["average calculation", "find minimum", "C 배열 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "arrays", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_arrays_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Arrays - Real-Life Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The "find lowest age" algorithm seeds its tracking variable with the array's OWN first element (`int lowestAge = ages[0];`) rather than an arbitrary sentinel like 0 or -1 — a deliberate choice that avoids a subtle bug: seeding with 0 would falsely "win" against any array of all-positive ages that happens to not contain a lower value, since every real comparison would need explicit special-casing otherwise. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Average via accumulate-then-divide** — sum every element in a loop, then divide by the `sizeof`-derived length; requires a `float`/`double` result variable to avoid integer-division truncation. [S1]
|
||||
- **Find-minimum via self-seeded comparison** — initialize the tracking variable with the array's first element, then compare/update while looping through the REST. [S1]
|
||||
- **Skip-and-stop pattern reused** — the same `continue`-for-negatives, `break`-at-zero pattern from the Break/Continue chapter is reused here verbatim on an array. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Average calculation: `int ages[] = {20, 22, 18, 35, 48, 26, 87, 70}; float avg, sum = 0; int length = sizeof(ages) / sizeof(ages[0]); for (i = 0; i < length; i++) { sum += ages[i]; } avg = sum / length; printf("The average age is: %.2f", avg);`. [S1]
|
||||
- Find-minimum via self-seeding: `int lowestAge = ages[0]; for (i = 0; i < length; i++) { if (lowestAge > ages[i]) { lowestAge = ages[i]; } }`. [S1]
|
||||
- Skip negatives, stop at zero: `int myNumbers[] = {3, -1, 7, 0, 9}; for (i = 0; i < length; i++) { if (myNumbers[i] < 0) { continue; } if (myNumbers[i] == 0) { break; } printf("%d\n", myNumbers[i]); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **최솟값 탐색 시 0이 아닌 첫 원소로 초기화하는 이유**: lowestAge를 0으로 초기화하면 모든 나이가 양수인 배열에서 항상 0이 "이겨버리는" 오류가 생기므로, 배열의 첫 원소로 초기화하는 것이 안전하다는 점이 예제 설계에서 암묵적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
나이 목록의 평균과 최솟값을 계산하는 두 예제가 원문에서 직접 실전 활용 사례로 제시되며, sizeof 기반 length 계산과 배열 순회 패턴을 실제 통계 계산에 적용하는 방법을 보여준다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Finding the minimum value by seeding the tracker with the array's own first element (C):
|
||||
```c
|
||||
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
|
||||
int length = sizeof(ages) / sizeof(ages[0]);
|
||||
int lowestAge = ages[0];
|
||||
int i;
|
||||
for (i = 0; i < length; i++) {
|
||||
if (lowestAge > ages[i]) {
|
||||
lowestAge = ages[i];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Arrays Multi]], [[C Break Continue]], [[C Structs]]
|
||||
- **참조 맥락:** 배열 섹션 마지막 — 구조체(Structs) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Arrays - Real-Life Examples — https://www.w3schools.com/c/c_arrays_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Arrays - Real-Life Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-arrays-size
|
||||
title: "C Array Size"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["sizeof array", "array length formula", "C 배열 크기"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "arrays", "sizeof"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_arrays_size.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Array Size]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`sizeof(array)` on a 5-element `int` array returns `20`, NOT `5` — a result that looks wrong until you remember `sizeof` reports total BYTES, not element count (4 bytes/int × 5 elements = 20) — meaning getting the actual element count requires an additional division step (`sizeof(arr) / sizeof(arr[0])`), a two-part formula that generalizes to arrays of ANY type since it divides the array's total size by one element's size rather than assuming a fixed per-element byte count. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`sizeof(array)`** — returns the array's TOTAL memory footprint in bytes, not its element count. [S1]
|
||||
- **Element-count formula** — `sizeof(array) / sizeof(array[0])` divides total bytes by one element's byte size, yielding the actual number of elements. [S1]
|
||||
- **Type-agnostic formula** — works identically for `int`, `double`, or any other array element type, since it never hardcodes a byte size. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Raw byte-size result (surprising to beginners): `int myNumbers[] = {10, 25, 50, 75, 100}; printf("%zu", sizeof(myNumbers)); // Prints 20 (not 5)`. [S1]
|
||||
- Correct element-count formula: `int length = sizeof(myNumbers) / sizeof(myNumbers[0]); printf("%d", length); // Prints 5`. [S1]
|
||||
- Same formula applied to a `double` array: `double myValues[] = {1.1, 2.2, 3.3}; int length = sizeof(myValues) / sizeof(myValues[0]); printf("%d", length); // Prints 3`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **sizeof(배열)은 요소 개수가 아니라 바이트 수를 반환**: 5개짜리 int 배열의 sizeof가 5가 아니라 20(4바이트×5)이라는 점이 초심자에게 혼동을 줄 수 있는 부분으로 명시적으로 설명됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 챕터에서 배운 sizeof(arr)/sizeof(arr[0]) 공식이 다음 챕터(Array Loop)에서 자동으로 크기에 적응하는 반복문을 만드는 데 바로 재사용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The type-agnostic formula for getting an array's actual element count (C):
|
||||
```c
|
||||
int myNumbers[] = {10, 25, 50, 75, 100};
|
||||
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
|
||||
printf("%d", length); // Prints 5, not 20
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Arrays]], [[C Data Types Sizeof]], [[C Arrays Loop]]
|
||||
- **참조 맥락:** 배열 크기 계산 공식 — 배열 반복문(Arrays Loop) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Array Size — https://www.w3schools.com/c/c_arrays_size.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Array Size" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-bitwise-operators
|
||||
title: "C Bitwise Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["& | ^ ~ << >>", "flags and permissions", "two's complement", "C 비트 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "bitwise"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_bitwise_operators.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Bitwise Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The bitwise NOT example (`~5` = `-6`) only makes sense once you know C stores negative numbers via TWO'S COMPLEMENT — flipping `00000101` (5) bit-by-bit gives `11111010`, which under two's complement representation is interpreted as -6, not some arbitrary large positive number — meaning `~` behaves "unexpectedly" only if you forget that the CPU's negative-number encoding, not simple bit-flipping intuition, determines the final printed value. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Six bitwise operators** — `&` (AND, 1 only if both bits 1), `|` (OR, 1 if either bit 1), `^` (XOR, 1 only if bits differ), `~` (NOT, inverts all bits), `<<` (left shift, multiplies by powers of 2), `>>` (right shift, divides by powers of 2). [S1]
|
||||
- **Integer-only operation** — bitwise operators only work on integer types (`int`, `char`, `long`), not floats. [S1]
|
||||
- **Two's complement interpretation** — `~a` inverting bits produces a result whose printed decimal value depends on how negative numbers are stored (typically two's complement). [S1]
|
||||
- **Flags pattern** — combining multiple boolean options into one integer using distinct bit positions (`#define READ 1`, `#define WRITE 2`, `#define EXEC 4`), then checking each with `&`. [S1]
|
||||
- **Shift as multiply/divide by powers of 2** — `a << n` multiplies `a` by 2ⁿ; `a >> n` divides `a` by 2ⁿ (sign bit may be preserved on signed integers, system-dependent). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Full worked example with `a = 6` (0110) and `b = 3` (0011): `a & b` = 2 (0010), `a | b` = 7 (0111), `a ^ b` = 5 (0101), `~a` = -7 on most systems, `a << 1` = 12 (1100), `a >> 1` = 3 (0011). [S1]
|
||||
- Bitwise NOT and two's complement: `int a = 5; // 00000101 int result = ~a; // -6 on most systems` — because inverted bits `11111010` are interpreted as -6 under two's complement. [S1]
|
||||
- Flags/permissions pattern: `#define READ 1 #define WRITE 2 #define EXEC 4 int permissions = READ | WRITE; if (permissions & READ) { printf("Read allowed\n"); } if (permissions & WRITE) { printf("Write allowed\n"); } if (permissions & EXEC) { printf("Execute allowed\n"); }` — only Read/Write print, since EXEC was never OR'd in. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **~ 연산 결과는 이진수 반전 자체가 아니라 2의 보수 해석에 좌우됨**: 5(00000101)를 반전하면 11111010이 되는데, 이를 그대로 큰 양수로 읽는 것이 아니라 대부분의 시스템에서 -6으로 해석된다는 점(2의 보수 표현)이 명시적으로 설명됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
READ/WRITE/EXEC 권한을 하나의 정수에 비트 플래그로 저장하고 &로 개별 권한을 검사하는 패턴이 원문에서 직접 실전 활용 사례로 제시됨(파일 시스템 권한 모델의 기초). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Storing multiple boolean options in a single integer using bit flags (C):
|
||||
```c
|
||||
#define READ 1 // 0001
|
||||
#define WRITE 2 // 0010
|
||||
#define EXEC 4 // 0100
|
||||
int permissions = READ | WRITE; // user can read and write
|
||||
if (permissions & READ) { printf("Read allowed\n"); }
|
||||
if (permissions & WRITE) { printf("Write allowed\n"); }
|
||||
if (permissions & EXEC) { printf("Execute allowed\n"); } // not printed
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators Logical]], [[C Operators Assignment]], [[C Operators Precedence]]
|
||||
- **참조 맥락:** 비트 연산자 — 연산자 우선순위(Operators Precedence) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Bitwise Operators — https://www.w3schools.com/c/c_bitwise_operators.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Bitwise Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-booleans
|
||||
title: "C Booleans"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["bool type", "stdbool.h", "C 불리언"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "booleans", "stdbool"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_booleans.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Booleans]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`bool` is NOT a built-in C type like `int` or `char` — it was only added in C99 and requires explicitly including `<stdbool.h>`, meaning code written for older/stricter C standards, or code that forgets this include, has no `bool` keyword at all and must fall back to plain `int` with 1/0 conventions instead. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`bool`** (C99+, via `<stdbool.h>`) — a type representing exactly two values: `true` or `false`. [S1]
|
||||
- **Underlying integer representation** — booleans print as integers: `1` (or any non-zero) for true, `0` for false, using the `%d` specifier. [S1]
|
||||
- **Bool-to-bool comparison** — bool variables can be compared with `==` just like any other value (e.g. checking if two bools are both true). [S1]
|
||||
- **Storing comparison results** — a comparison's result (already a 1/0 value) can be stored directly in a `bool` variable for readability and reuse. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Declaring and printing bools: `bool isProgrammingFun = true; bool isFishTasty = false; printf("%d", isProgrammingFun); // 1 printf("%d", isFishTasty); // 0`. [S1]
|
||||
- Comparing two bool variables: `bool isHamburgerTasty = true; bool isPizzaTasty = true; printf("%d", isHamburgerTasty == isPizzaTasty); // 1`. [S1]
|
||||
- Storing a comparison result in a bool: `int x = 10; int y = 9; bool isGreater = x > y; printf("%d", isGreater); // 1`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **bool은 C의 내장 타입이 아님**: int나 char와 달리 bool은 C99에서 도입되었고 반드시 <stdbool.h>를 포함해야 사용 가능하다는 점이 명시적으로 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 비교 결과를 bool 변수에 저장해 재사용하는 것이 코드 가독성을 높이는 실전 습관으로 권장된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Storing a comparison's result in a bool variable for readability (C):
|
||||
```c
|
||||
#include <stdbool.h>
|
||||
int x = 10;
|
||||
int y = 9;
|
||||
bool isGreater = x > y;
|
||||
printf("%d", isGreater); // Prints 1 (true)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Random Numbers]], [[C Operators Comparison]], [[C Booleans RealLife]]
|
||||
- **참조 맥락:** 불리언 섹션 첫 챕터 — 불리언 실전 예제(Booleans RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Booleans — https://www.w3schools.com/c/c_booleans.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Booleans" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-booleans-reallife
|
||||
title: "C Boolean Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["voting age example", "boolean if-else preview", "C 불리언 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "booleans", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_booleans_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Boolean Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
This chapter explicitly reframes the entire preceding Comparison/Boolean material as mere PREPARATION for `if...else` — printing a raw `1` or `0` (as done in every earlier example) is functionally correct but not directly useful to an end user, and the source's own upgrade (wrapping the same comparison in `if (myAge >= votingAge) {...} else {...}`) shows that booleans are the evaluated CONDITION inside control flow, not typically an end product to display as-is. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Comparison as raw output** — printing a comparison directly (`printf("%d", myAge >= votingAge);`) shows 1 or 0, technically correct but not user-friendly. [S1]
|
||||
- **Comparison as an `if` condition** — the SAME comparison expression, placed inside `if (...)`, drives which branch of code executes, producing human-readable output instead of a raw 1/0. [S1]
|
||||
- **Booleans as the foundation of conditions** — the chapter explicitly states booleans "are the basis for all comparisons and conditions," directly foreshadowing the next chapter's Conditions/if-else content. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Raw comparison output: `int myAge = 25; int votingAge = 18; printf("%d", myAge >= votingAge); // Returns 1 (true)`. [S1]
|
||||
- The same logic upgraded into an if...else: `if (myAge >= votingAge) { printf("Old enough to vote!"); } else { printf("Not old enough to vote."); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
투표 가능 연령(18세) 확인 로직을 raw 1/0 출력에서 if...else로 업그레이드하는 것이 이 챕터가 직접 보여주는 실전 활용 사례이자, 다음 챕터(Conditions)로의 전환점이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The same boolean comparison used inside an if...else for human-readable output (C):
|
||||
```c
|
||||
int myAge = 25;
|
||||
int votingAge = 18;
|
||||
if (myAge >= votingAge) {
|
||||
printf("Old enough to vote!");
|
||||
} else {
|
||||
printf("Not old enough to vote.");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Booleans]], [[C Conditions]]
|
||||
- **참조 맥락:** 불리언 섹션 마지막 — 조건문(Conditions) 섹션으로 직접 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Boolean Examples — https://www.w3schools.com/c/c_booleans_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Boolean Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: c-break-continue
|
||||
title: "C Break and Continue"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["break statement", "continue statement", "loop control", "C break continue"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "break", "continue"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_break_continue.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Break and Continue]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`break` and `continue` are the same two keywords across BOTH switch statements and loops, but their meaning shifts by context — the source explicitly notes `break` was already seen "jumping out" of a `switch` block, and here it does the analogous thing for a LOOP (stop entirely), while `continue` has no switch equivalent at all — meaning `break`'s core behavior ("exit the current block early") generalizes across constructs, but `continue`'s "skip to next iteration" concept is loop-specific. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`break`** — stops the loop COMPLETELY, immediately, regardless of remaining iterations. [S1]
|
||||
- **`continue`** — skips the REST of the current iteration's body and jumps straight to the next iteration (does not stop the loop). [S1]
|
||||
- **Combinability** — `break` and `continue` can coexist in the same loop, each triggered by different conditions. [S1]
|
||||
- **Works in both `for` and `while` loops** — the same semantics apply regardless of loop type. [S1]
|
||||
- **Real-world pattern: skip-then-stop** — using `continue` to skip invalid/unwanted values while using `break` to halt entirely on a sentinel value (like a zero marking "end of valid data"). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- `break` stopping a for loop at i==4: `for (i = 0; i < 10; i++) { if (i == 4) { break; } printf("%d\n", i); }` — prints 0,1,2,3 then stops entirely. [S1]
|
||||
- `continue` skipping just one value: `for (i = 0; i < 10; i++) { if (i == 4) { continue; } printf("%d\n", i); }` — prints 0,1,2,3,5,6,7,8,9 (skips only 4). [S1]
|
||||
- Combined in one loop: `for (i = 0; i < 6; i++) { if (i == 2) { continue; } if (i == 4) { break; } printf("%d\n", i); }` — prints 0,1,3 then stops at 4. [S1]
|
||||
- Real-life skip-negatives-stop-at-zero pattern: `int myNumbers[] = {3, -1, 7, 0, 9}; for (i = 0; i < length; i++) { if (myNumbers[i] < 0) { continue; } if (myNumbers[i] == 0) { break; } printf("%d\n", myNumbers[i]); }` — prints 3 and 7, skips -1, stops entirely at 0 (never reaching 9). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **break와 continue의 근본적 차이**: break는 루프를 완전히 종료하지만 continue는 현재 회차만 건너뛰고 루프는 계속된다는 점이 "Good to Remember" 요약으로 명확히 구분됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
음수는 건너뛰고(continue) 0을 만나면 완전히 멈추는(break) 숫자 리스트 처리 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Combining continue (skip invalid values) and break (stop at a sentinel value) in one loop (C):
|
||||
```c
|
||||
int myNumbers[] = {3, -1, 7, 0, 9};
|
||||
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
|
||||
int i;
|
||||
for (i = 0; i < length; i++) {
|
||||
if (myNumbers[i] < 0) {
|
||||
continue; // skip negative numbers
|
||||
}
|
||||
if (myNumbers[i] == 0) {
|
||||
break; // stop loop when zero is found
|
||||
}
|
||||
printf("%d\n", myNumbers[i]);
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C For Loop RealLife]], [[C Switch]], [[C Arrays]]
|
||||
- **참조 맥락:** 반복문 섹션 마지막 — 배열(Arrays) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Break and Continue — https://www.w3schools.com/c/c_break_continue.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Break and Continue" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-comments
|
||||
title: "C Comments"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["single-line comments", "multi-line comments", "C 주석"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "comments"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_comments.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Comments]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Before C99 (1999), single-line `//` comments were NOT part of standard C at all — only `/* */` multi-line comments existed — meaning `//` comments, now the default choice for short notes, are actually a relatively recent addition to the language's ~50-year history, not an original feature. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Single-line comments (`//`)** — everything from `//` to the end of the line is ignored by the compiler. [S1]
|
||||
- **Multi-line comments (`/* */`)** — everything between the markers is ignored, regardless of line count. [S1]
|
||||
- **Comments as code-disabling tool** — `//` can be prefixed to a line of working code to temporarily disable it during testing, without deleting it. [S1]
|
||||
- **Historical constraint** — pre-C99, only `/* */` was valid; `//` support was added in the C99 standard. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Single-line comment before code: `// This is a comment` followed by `printf("Hello World!");`. [S1]
|
||||
- Single-line comment disabling code: `printf("This will run"); // printf("This will NOT run");`. [S1]
|
||||
- Multi-line comment: `/* The code below will print the words Hello World! to the screen, and it is amazing */ printf("Hello World!");`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **// 주석의 표준화 시점**: C99(1999) 이전에는 다중 줄 주석(/* */)만 사용 가능했고, 한 줄 주석(//)은 C99부터 표준에 포함되었다는 역사적 사실이 명시됨 — 구형 컴파일러/표준 준수 코드 작성 시 유의해야 할 사항. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 특정 코드 줄을 지우지 않고 // 로 임시 비활성화하는 것이 실전 디버깅/테스트에서 흔히 쓰이는 기법이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Temporarily disabling a line of code using a single-line comment instead of deleting it (C):
|
||||
```c
|
||||
printf("This will run");
|
||||
// printf("This will NOT run");
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Output]], [[C Organize Code]]
|
||||
- **참조 맥락:** 주석 문법 — 코드 조직화(Organize Code) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Comments — https://www.w3schools.com/c/c_comments.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Comments" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-conditions
|
||||
title: "C If ... Else"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["if statement", "lowercase if", "C 조건문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "if-statement"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C If ... Else]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Case sensitivity isn't just a general C rule mentioned in passing — this chapter singles it out specifically for `if`, explicitly warning that `If` or `IF` will generate an error, meaning the keyword has zero tolerance for capitalization variants despite `if` being one of the most frequently typed words in any C program. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Six comparison conditions** — `<`, `<=`, `>`, `>=`, `==`, `!=`, familiar from mathematics. [S1]
|
||||
- **Four conditional constructs** — `if` (run code if true), `else` (run if false), `else if` (test a new condition if the first is false), `switch` (many alternative code blocks). [S1]
|
||||
- **Case-sensitive keyword** — `if` must be lowercase; `If`/`IF` produce an error. [S1]
|
||||
- **Boolean-variable readability pattern** — storing a comparison's result in a `bool` variable before using it in `if` makes complex or reused conditions easier to read. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic if with literal values: `if (20 > 18) { printf("20 is greater than 18"); }`. [S1]
|
||||
- If with variables: `int x = 20; int y = 18; if (x > y) { printf("x is greater than y"); }`. [S1]
|
||||
- Using a boolean variable to hold the condition: `bool isGreater = x > y; if (isGreater) { printf("x is greater than y"); }` (requires `<stdbool.h>`). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **if는 반드시 소문자**: If나 IF처럼 대소문자를 다르게 쓰면 에러가 발생한다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 복잡하거나 재사용되는 조건을 bool 변수에 미리 담아두는 패턴이 가독성 있는 조건문 작성의 실전 관행이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Storing a condition in a readable boolean variable before using it in an if statement (C):
|
||||
```c
|
||||
int x = 20;
|
||||
int y = 18;
|
||||
bool isGreater = x > y;
|
||||
if (isGreater) {
|
||||
printf("x is greater than y");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Booleans RealLife]], [[C Conditions Else]]
|
||||
- **참조 맥락:** 조건문 섹션 첫 챕터 — else 문(Conditions Else) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C If ... Else — https://www.w3schools.com/c/c_conditions.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C If ... Else" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-conditions-else
|
||||
title: "C Else"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["else statement", "C else 문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "else"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_else.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Else]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Naming a boolean condition variable descriptively (`isDay` instead of a raw `time < 18` expression) doesn't change the program's behavior at all — it's purely a communication device for future readers — and the source explicitly frames this as its entire justification: "makes it easy to understand what the condition means," not a performance or correctness improvement. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`else`** — runs a block of code when the paired `if` condition is false; there is no separate condition to check for `else` itself. [S1]
|
||||
- **Mutually exclusive branches** — exactly one of the `if` or `else` block executes, never both, never neither. [S1]
|
||||
- **Descriptive boolean naming** — storing a condition in a variable like `isDay` documents the condition's MEANING, not just its mechanics. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic if/else: `int time = 20; if (time < 18) { printf("Good day."); } else { printf("Good evening."); } // Outputs "Good evening."`. [S1]
|
||||
- Same logic with a descriptively-named boolean: `bool isDay = time < 18; if (isDay) { printf("Good day."); } else { printf("Good evening."); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
시간(time)이 18보다 작은지에 따라 "좋은 하루"/"좋은 저녁"을 출력하는 예제가 원문에서 직접 실전 활용 사례로 제시됨(시간대 기반 인사말 로직). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Naming a boolean condition descriptively for readability (C):
|
||||
```c
|
||||
int time = 20;
|
||||
bool isDay = time < 18;
|
||||
if (isDay) {
|
||||
printf("Good day.");
|
||||
} else {
|
||||
printf("Good evening.");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions]], [[C Conditions ElseIf]]
|
||||
- **참조 맥락:** else 문 — else if 문(Conditions ElseIf) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Else — https://www.w3schools.com/c/c_conditions_else.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Else" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-conditions-elseif
|
||||
title: "C Else If"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["else if chain", "top to bottom evaluation", "C else if 문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "else-if"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_elseif.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Else If]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Conditions in an if/else-if chain are checked strictly top-to-bottom and STOP at the first true match — the source's time example explicitly notes "as soon as one condition is true, its block of code runs, and the rest are skipped," meaning even if a later condition would ALSO be true, only the FIRST matching branch ever executes; chain ORDER therefore determines behavior, not just correctness of each individual condition. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`else if`** — tests a new condition only if the preceding condition(s) were false; can be chained multiple times. [S1]
|
||||
- **First-match-wins evaluation** — conditions are checked top to bottom; the FIRST true condition's block runs and all subsequent conditions in the chain are skipped, even if they'd also evaluate true. [S1]
|
||||
- **Boolean-variable chaining** — each condition in the chain can be pre-computed into a descriptively-named bool (`isMorning`, `isDay`) for readability. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Time-of-day chain: `int time = 16; if (time < 12) { printf("Good morning."); } else if (time < 18) { printf("Good day."); } else { printf("Good evening."); } // Outputs "Good day."` — the first condition (`time < 12`) is false, the second (`time < 18`) is true, so only "Good day." prints. [S1]
|
||||
- Same chain with named booleans: `bool isMorning = time < 12; bool isDay = time < 18; if (isMorning) {...} else if (isDay) {...} else {...}`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **첫 번째로 참인 조건만 실행됨**: 체인 내 여러 조건이 이론상 동시에 참일 수 있어도, 위에서부터 먼저 참으로 판정된 조건의 블록만 실행되고 나머지는 건너뛴다는 점이 명시적으로 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 시간대에 따라 아침/낮/저녁 인사를 구분하는 것이 else if 체인의 대표적인 실전 활용 예시다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Chained else-if conditions evaluated top-to-bottom, stopping at the first match (C):
|
||||
```c
|
||||
int time = 16;
|
||||
if (time < 12) {
|
||||
printf("Good morning.");
|
||||
} else if (time < 18) {
|
||||
printf("Good day.");
|
||||
} else {
|
||||
printf("Good evening.");
|
||||
}
|
||||
// Outputs "Good day."
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions Else]], [[C Conditions Short Hand]]
|
||||
- **참조 맥락:** else if 체인 — 삼항 연산자(Conditions Short Hand) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Else If — https://www.w3schools.com/c/c_conditions_elseif.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Else If" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: c-conditions-logical
|
||||
title: "C Logical Operators in Conditions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["access control logic", "&& || ! in if", "C 조건문 논리 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "logical-operators"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_logical.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Logical Operators in Conditions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The access-control example composes THREE logical operators into one nested rule — `isLoggedIn && (isAdmin || securityLevel <= 2)` — which the source walks through with four distinct securityLevel values (1, 2, 3, 4) to show the exact boundary where access flips from granted to denied, demonstrating that real authorization logic is rarely a single comparison but a nested AND/OR combination whose behavior must be traced case by case, not just read at a glance. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`&&` (AND) in conditions** — both conditions must be true for the combined condition to be true. [S1]
|
||||
- **`||` (OR) in conditions** — at least one condition must be true. [S1]
|
||||
- **`!` (NOT) in conditions** — reverses a condition's truth value (true↔false); useful for phrasing "check that something is NOT the case." [S1]
|
||||
- **Nested logical composition** — parentheses group sub-conditions (e.g. `(isAdmin || securityLevel <= 2)`) that then combine with another condition via `&&`, mirroring real authorization rules. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- AND: `int a = 200, b = 33, c = 500; if (a > b && c > a) { printf("Both conditions are true\n"); }`. [S1]
|
||||
- OR: `if (a > b || a > c) { printf("At least one condition is true\n"); }`. [S1]
|
||||
- NOT: `int a = 33; int b = 200; if (!(a > b)) { printf("a is NOT greater than b\n"); }`. [S1]
|
||||
- Full access-control rule with worked-through outcomes: `bool isLoggedIn = true; bool isAdmin = false; int securityLevel = 3; if (isLoggedIn && (isAdmin || securityLevel <= 2)) { printf("Access granted\n"); } else { printf("Access denied\n"); }` — securityLevel 1 or 2 → granted; 3 or 4 → denied (unless isAdmin is true, which always grants access). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
로그인 여부(isLoggedIn) + (관리자이거나(isAdmin) 보안등급이 2 이하(securityLevel <= 2))를 결합한 접근 제어 규칙이 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Nested AND/OR logic for a real-world access-control rule (C):
|
||||
```c
|
||||
bool isLoggedIn = true;
|
||||
bool isAdmin = false;
|
||||
int securityLevel = 3; // 1 = highest
|
||||
if (isLoggedIn && (isAdmin || securityLevel <= 2)) {
|
||||
printf("Access granted\n");
|
||||
} else {
|
||||
printf("Access denied\n");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions Short Hand]], [[C Operators Logical]], [[C Conditions Nested]]
|
||||
- **참조 맥락:** 조건문 내 논리 연산자 — 중첩 if(Conditions Nested) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Logical Operators in Conditions — https://www.w3schools.com/c/c_conditions_logical.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Logical Operators in Conditions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: c-conditions-nested
|
||||
title: "C Nested If"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["if inside if", "dependent conditions", "C 중첩 if"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "nested-if"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_nested.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Nested If]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A nested `if` only ever gets EVALUATED at all if the outer condition is true — the voting-and-citizenship example never even checks `isCitizen` if `age >= 18` is false, meaning nesting isn't just visual grouping of related checks, it's a genuine short-circuit optimization where the inner condition's cost (and its own true/false branches) is entirely skipped when the outer gate fails. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Nested if** — placing an `if` statement inside another `if`'s block, so the inner condition is only checked when the outer condition is already true. [S1]
|
||||
- **Dependent condition modeling** — naturally expresses "check B only if A holds" logic, like age eligibility gating a citizenship check. [S1]
|
||||
- **Depth caution** — the source explicitly warns against nesting too deeply, as it can hurt readability; nested if is commonly combined with `else`/`else if` for richer decision trees. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic two-level nesting: `int x = 15; int y = 25; if (x > 10) { printf("x is greater than 10\n"); if (y > 20) { printf("y is also greater than 20\n"); } }` — both print since both conditions hold. [S1]
|
||||
- Voting + citizenship real-life example: `int age = 20; bool isCitizen = true; if (age >= 18) { printf("Old enough to vote.\n"); if (isCitizen) { printf("And you are a citizen, so you can vote!\n"); } else { printf("But you must be a citizen to vote.\n"); } } else { printf("Not old enough to vote.\n"); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **중첩 if의 단축 평가 효과**: 바깥 조건이 거짓이면 안쪽 if의 조건 자체가 아예 평가되지 않는다는 점이 나이/시민권 예제로 확인됨 — 관련 없는 하위 조건을 불필요하게 검사하지 않는 효율성을 제공. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
투표 가능 연령(18세 이상)을 먼저 확인하고, 그 안에서만 시민권 여부를 추가로 확인하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
An inner condition (citizenship) checked only when the outer condition (age) already holds (C):
|
||||
```c
|
||||
int age = 20;
|
||||
bool isCitizen = true;
|
||||
if (age >= 18) {
|
||||
printf("Old enough to vote.\n");
|
||||
if (isCitizen) {
|
||||
printf("And you are a citizen, so you can vote!\n");
|
||||
} else {
|
||||
printf("But you must be a citizen to vote.\n");
|
||||
}
|
||||
} else {
|
||||
printf("Not old enough to vote.\n");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions Logical]], [[C Conditions RealLife]]
|
||||
- **참조 맥락:** 중첩 if — 조건문 실전 예제(Conditions RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Nested If — https://www.w3schools.com/c/c_conditions_nested.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Nested If" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-conditions-reallife
|
||||
title: "C If ... Else Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["real-life if else", "even or odd example", "C 조건문 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C If ... Else Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The even/odd checker reuses the `%` modulus operator from the Arithmetic Operators chapter for a purpose that has nothing to do with "remainder after division" in the everyday sense — `myNum % 2 == 0` is the standard idiom for parity checking, showing that modulus's real-world utility often lies in binary classification (even/odd, every-Nth) rather than literal division-remainder arithmetic. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **This chapter is a compilation** — six worked real-life if/else scenarios, consolidating patterns from every prior Conditions sub-chapter (basic if/else, else-if chains, nested if, logical operators). [S1]
|
||||
- **Door-code check** — a single `==` equality check gating access. [S1]
|
||||
- **Positive/negative/zero classification** — a three-way `if`/`else if`/`else` chain covering all three number sign cases. [S1]
|
||||
- **Even/odd via modulus** — `num % 2 == 0` is the standard parity-check idiom. [S1]
|
||||
- **Temperature banding** — a three-tier `if`/`else if`/`else` chain (freezing/cool/warm) based on numeric thresholds. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Door code check: `int doorCode = 1337; if (doorCode == 1337) { printf("Correct code.\nThe door is now open."); } else { printf("Wrong code.\nThe door remains closed."); }`. [S1]
|
||||
- Positive/negative/zero: `int myNum = 10; if (myNum > 0) { printf("The value is a positive number."); } else if (myNum < 0) { printf("The value is a negative number."); } else { printf("The value is 0."); }`. [S1]
|
||||
- Even/odd check: `int myNum = 5; if (myNum % 2 == 0) { printf("%d is even.\n", myNum); } else { printf("%d is odd.\n", myNum); }`. [S1]
|
||||
- Temperature banding: `int temperature = 30; if (temperature < 0) { printf("It's freezing!\n"); } else if (temperature < 20) { printf("It's cool.\n"); } else { printf("It's warm.\n"); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
도어락 코드 확인, 숫자 부호 판별, 짝/홀수 판별, 온도 구간 분류, 접근 제어 등 6가지 실전 시나리오가 원문에서 직접 제시되며, 각각이 조건문 섹션 전체를 종합한 실전 활용 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The standard parity-check idiom using the modulus operator (C):
|
||||
```c
|
||||
int myNum = 5;
|
||||
if (myNum % 2 == 0) {
|
||||
printf("%d is even.\n", myNum);
|
||||
} else {
|
||||
printf("%d is odd.\n", myNum);
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions Nested]], [[C Operators Arithmetic]], [[C Switch]]
|
||||
- **참조 맥락:** 조건문 섹션 마지막 — switch 문(Switch) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C If ... Else Examples — https://www.w3schools.com/c/c_conditions_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C If ... Else Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: c-conditions-short-hand
|
||||
title: "C Short Hand If Else"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["ternary operator", "condition ? true : false", "C 삼항 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "conditions", "ternary-operator"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_conditions_short_hand.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Short Hand If Else]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The ternary operator is explicitly named for its OPERAND COUNT — "because it uses three operands" (condition, true-expression, false-expression) — not because of any special syntax category, meaning it's simply the only operator in C that takes three arguments rather than the usual one or two, which is why it stands out enough to warrant special naming. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Ternary operator (`?:`)** — a shorthand if/else that RETURNS a value rather than branching execution; syntax: `variable = (condition) ? expressionTrue : expressionFalse;`. [S1]
|
||||
- **Three operands** — condition, true-branch expression, false-branch expression — the origin of the name "ternary." [S1]
|
||||
- **Equivalent to a simple if/else** — best suited for replacing straightforward two-branch if/else statements, not complex multi-branch logic. [S1]
|
||||
- **Stylistic choice** — the source explicitly states it's "completely up to you" whether to use traditional if/else or the ternary form. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Traditional if/else form: `int time = 20; if (time < 18) { printf("Good day."); } else { printf("Good evening."); }`. [S1]
|
||||
- Equivalent one-line ternary form: `int time = 20; (time < 18) ? printf("Good day.") : printf("Good evening.");`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 시간에 따른 인사말 출력을 한 줄로 압축하는 예제가 삼항 연산자의 대표 실전 활용이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A simple if/else compressed into one line using the ternary operator (C):
|
||||
```c
|
||||
int time = 20;
|
||||
(time < 18) ? printf("Good day.") : printf("Good evening.");
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions ElseIf]], [[C Conditions Logical]]
|
||||
- **참조 맥락:** 삼항 연산자 — 조건문 내 논리 연산자(Conditions Logical) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Short Hand If Else — https://www.w3schools.com/c/c_conditions_short_hand.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Short Hand If Else" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-constants
|
||||
title: "C Constants"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["const keyword", "read-only variables", "C 상수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "constants"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_constants.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Constants]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A `const` variable MUST be assigned a value at the moment of declaration — declaring it first and assigning later (`const int minutesPerHour; minutesPerHour = 60;`) is explicitly shown as an error — meaning `const` isn't just "can't change later," it also removes the two-step declare-then-assign pattern that ordinary variables freely support. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`const` keyword** — makes a variable unchangeable/read-only after its initial assignment. [S1]
|
||||
- **Mandatory initialization** — a `const` variable must receive its value at declaration time; assigning it afterward is a compile error. [S1]
|
||||
- **Uppercase naming convention** — while not required, C programmers commonly write constant names in uppercase (e.g. `BIRTHYEAR`) for readability. [S1]
|
||||
- **Use case** — values unlikely to ever change during program execution (e.g. `minutesPerHour`, `monthsInYear`). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Attempting reassignment fails: `const int myNum = 15; myNum = 10; // error: assignment of read-only variable 'myNum'`. [S1]
|
||||
- Declare-without-assign fails: `const int minutesPerHour; minutesPerHour = 60; // error`. [S1]
|
||||
- Uppercase convention: `const int BIRTHYEAR = 1980;`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **const는 선언과 동시에 초기화 필수**: 일반 변수처럼 먼저 선언만 하고 나중에 값을 대입하는 방식이 const에서는 컴파일 에러를 발생시킨다는 점이 명시적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 시간당 분(60), 연중 개월 수(12)처럼 절대 변하지 않는 값을 const로 선언하는 것이 실전 코드에서의 표준 활용이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Declaring constants that must be initialized at the point of declaration (C):
|
||||
```c
|
||||
const int minutesPerHour = 60;
|
||||
const int monthsInYear = 12;
|
||||
const int BIRTHYEAR = 1980; // uppercase is a common naming convention
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types RealLife]], [[C Storage Classes]]
|
||||
- **참조 맥락:** 상수 선언 — 저장 클래스(Storage Classes) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Constants — https://www.w3schools.com/c/c_constants.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Constants" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-data-types
|
||||
title: "C Data Types"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["int float double char", "format specifiers table", "C 데이터 타입"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Data Types]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source's explicit warning — "if not [using the correct format specifier], the program may produce errors or even crash" — reveals that in C, a format specifier mismatch isn't just a display glitch like in more forgiving languages; it can cause undefined behavior or a crash, because `printf()` blindly trusts the specifier to know how many bytes to read from the argument list. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Four basic types** — `int` (2 or 4 bytes, whole numbers), `float` (4 bytes, ~6-7 decimal digit precision), `double` (8 bytes, ~15 decimal digit precision), `char` (1 byte, single character/ASCII value). [S1]
|
||||
- **Type-specific format specifiers** — `%d`/`%i` (int), `%f`/`%F` (float), `%lf` (double), `%c` (char), `%s` (string, covered later). [S1]
|
||||
- **Mismatch risk** — using the wrong specifier for a type can cause errors or crashes, not just wrong output. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Four types declared and printed together: `int myNum = 5; float myFloatNum = 5.99; char myLetter = 'D'; printf("%d\n", myNum); printf("%f\n", myFloatNum); printf("%c\n", myLetter);`. [S1]
|
||||
- Format specifier reference table: int→`%d`/`%i`, float→`%f`/`%F`, double→`%lf`, char→`%c`, string→`%s`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **잘못된 포맷 지정자의 실질적 위험**: 단순 출력 오류가 아니라 프로그램이 크래시할 수도 있다는 점이 명시적으로 경고됨 — printf()가 지정자만 보고 인자 크기를 추정하기 때문. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 정수/실수/문자 네 가지 기본 타입을 상황에 맞게 선택하는 것이 이후 모든 C 챕터의 기초가 된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The four basic C data types printed with their matching format specifiers:
|
||||
```c
|
||||
int myNum = 5; // Integer (whole number)
|
||||
float myFloatNum = 5.99; // Floating point number
|
||||
char myLetter = 'D'; // Character
|
||||
printf("%d\n", myNum);
|
||||
printf("%f\n", myFloatNum);
|
||||
printf("%c\n", myLetter);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables Format]], [[C Data Types Numbers]], [[C Data Types Characters]]
|
||||
- **참조 맥락:** 데이터 타입 섹션 첫 챕터 — 숫자형 타입 상세(Data Types Numbers) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Data Types — https://www.w3schools.com/c/c_data_types.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-data-types-characters
|
||||
title: "C Character Data Types"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["char type", "ASCII values", "C 문자 타입"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types", "char", "ascii"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_characters.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Character Data Types]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Assigning multiple characters to a single `char` variable (`char myText = 'Hello';`) doesn't raise an error — it silently prints only the LAST character — meaning `char`'s single-character limit is a silent-failure trap rather than a compile-time guard, and the source explicitly warns not to rely on it for anything beyond one character. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`char`** — stores exactly one character, written in single quotes (`'A'`), printed with `%c`. [S1]
|
||||
- **ASCII value assignment** — `char` variables can be assigned numeric ASCII codes directly (no quotes, since it's a number, not a literal character) and still print as the corresponding character via `%c`. [S1]
|
||||
- **Silent truncation on multi-character assignment** — `char myText = 'Hello';` compiles but only stores/prints the LAST character, with no error raised. [S1]
|
||||
- **Strings for multi-character text** — `char myText[] = "Hello";` (a character array, printed with `%s`) is the correct tool for multi-character text, not a bare `char`. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic char: `char myGrade = 'A'; printf("%c", myGrade);`. [S1]
|
||||
- ASCII numeric assignment: `char a = 65, b = 66, c = 67; printf("%c", a); printf("%c", b); printf("%c", c);` — prints A, B, C. [S1]
|
||||
- The silent-truncation trap: `char myText = 'Hello'; printf("%c", myText);` — prints only the last character, with no compiler error. [S1]
|
||||
- Correct multi-character storage: `char myText[] = "Hello"; printf("%s", myText);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **char에 여러 문자 대입 시 조용한 실패**: 'Hello'처럼 여러 문자를 char 변수에 대입해도 에러 없이 컴파일되지만 마지막 문자만 저장/출력된다는 점이 명시적으로 경고됨 — 여러 문자에는 반드시 문자열(char 배열)을 써야 함. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — ASCII 코드값(65,66,67)을 직접 char에 대입해 A/B/C를 출력하는 패턴이 문자와 숫자 표현이 내부적으로 같다는 것을 보여주는 실전 예시다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Assigning ASCII numeric codes directly to char variables (C):
|
||||
```c
|
||||
char a = 65, b = 66, c = 67;
|
||||
printf("%c", a); // A
|
||||
printf("%c", b); // B
|
||||
printf("%c", c); // C
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types Numbers]], [[C Data Types Dec]], [[C Strings]]
|
||||
- **참조 맥락:** 문자 타입과 ASCII — 소수점 정밀도(Data Types Dec) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Character Data Types — https://www.w3schools.com/c/c_data_types_characters.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Character Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-data-types-dec
|
||||
title: "C Decimal Precision"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["%.2f", "decimal precision", "C 소수점 자리수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types", "printf", "precision"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_dec.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Decimal Precision]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
By default `%f` always pads a float/double out to 6 digits after the decimal point regardless of how few digits the actual value has (`3.5` prints as `3.500000`) — meaning the visible "extra zeros" problem beginners see isn't a bug in their number, it's `%f`'s fixed default precision, controllable only by inserting a `.N` modifier between `%` and `f`. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Default `%f` precision** — always shows 6 digits after the decimal point, padding with zeros if the actual value has fewer. [S1]
|
||||
- **`.N` precision modifier** — inserting `.N` between `%` and `f` (e.g. `%.2f`) limits output to exactly N digits after the decimal point. [S1]
|
||||
- **Applies to both float and double** — the precision modifier syntax works the same way regardless of which type is being printed. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Default padding behavior: `float myFloatNum = 3.5; printf("%f\n", myFloatNum); // Outputs 3.500000`. [S1]
|
||||
- Controlling precision: `printf("%.1f\n", myFloatNum); // Only show 1 digit` / `printf("%.2f\n", myFloatNum); // Only show 2 digits` / `printf("%.4f", myFloatNum); // Only show 4 digits`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — %.2f로 소수점 둘째 자리까지만 표시하는 것이 통화 금액 출력(다음 Real-Life 예제의 총 비용 계산) 같은 실전 상황에서 표준적으로 쓰인다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Controlling how many decimal digits printf() shows (C):
|
||||
```c
|
||||
float myFloatNum = 3.5;
|
||||
printf("%f\n", myFloatNum); // Default: 3.500000
|
||||
printf("%.1f\n", myFloatNum); // 3.5
|
||||
printf("%.2f\n", myFloatNum); // 3.50
|
||||
printf("%.4f", myFloatNum); // 3.5000
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types Characters]], [[C Data Types Extended]], [[C Data Types RealLife]]
|
||||
- **참조 맥락:** 소수점 정밀도 제어 — 확장 타입(Data Types Extended) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Decimal Precision — https://www.w3schools.com/c/c_data_types_dec.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Decimal Precision" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-data-types-extended
|
||||
title: "C Extended Types"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["short long unsigned", "long long int", "C 확장 데이터 타입"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types", "extended-types"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_extended.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Extended Types]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The exact byte size of every extended type (`short int`, `long int`, etc.) is explicitly marked as SYSTEM-DEPENDENT, not a fixed language guarantee — `long int` might be 4 OR 8 bytes depending on whether the system is 32-bit or 64-bit and which compiler is used, meaning code relying on an assumed size can silently behave differently across machines unless the programmer verifies with `sizeof` or uses fixed-width types instead. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`short int`** — smaller range int, 2 bytes, `%hd`. [S1]
|
||||
- **`unsigned int`** — non-negative-only int, 2 or 4 bytes, `%u`. [S1]
|
||||
- **`long int` / `long long int`** — larger-range ints, 4-8 bytes, `%ld`/`%lld`. [S1]
|
||||
- **`unsigned long int` / `unsigned long long int`** — non-negative, larger range, `%lu`/`%llu`. [S1]
|
||||
- **`long double`** — extended precision beyond `double`, 8-16 bytes, `%Lf`. [S1]
|
||||
- **`unsigned`** — a modifier meaning the type can only store 0 and positive values, trading away negative range for extra positive headroom. [S1]
|
||||
- **Platform-dependent sizes** — sizes differ across systems (older/newer, 32-bit/64-bit, compiler); use `sizeof` to check actual sizes, or fixed-width types (covered later) when exact size matters. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Full extended-type example: `short int small = -100; unsigned int count = 25; long int big = 1234567890; long long int veryBig = 9223372036854775807; unsigned long long int huge = 18446744073709551615U; long double precise = 3.141592653589793238L;` printed with `%hd`/`%u`/`%ld`/`%lld`/`%llu`/`%Lf` respectively. [S1]
|
||||
- Checking actual sizes on the current system: `printf("Size of long int: %zu bytes\n", sizeof(long int));`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **확장 타입 크기는 시스템 의존적**: long int가 시스템에 따라 4바이트 또는 8바이트일 수 있다는 점이 명시되며, 정확한 크기가 필요하면 sizeof로 확인하거나 고정폭 정수 타입(Fixed Width Ints)을 사용하라고 안내됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 일상적인 프로그래밍에서는 int/float/double/char로 충분하며, 확장 타입은 메모리나 숫자 범위를 정밀 제어해야 할 때만 필요하다고 명시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Declaring and printing several extended integer types (C):
|
||||
```c
|
||||
long long int veryBig = 9223372036854775807;
|
||||
unsigned long long int huge = 18446744073709551615U;
|
||||
printf("Very Big: %lld\n", veryBig);
|
||||
printf("Huge: %llu\n", huge);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types Dec]], [[C Data Types Sizeof]], [[C Fixed Width Ints]]
|
||||
- **참조 맥락:** 확장 정수 타입 — sizeof 연산자(Data Types Sizeof) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Extended Types — https://www.w3schools.com/c/c_data_types_extended.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Extended Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-data-types-numbers
|
||||
title: "C Numeric Data Types"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["float vs double", "scientific notation", "C 숫자 타입"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types", "numbers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_numbers.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Numeric Data Types]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source explicitly recommends `double` over `float` as the SAFER DEFAULT for "most calculations" despite `double` costing twice the memory (8 bytes vs 4) — reframing the float/double choice not as "smaller is better" but as a precision-vs-memory tradeoff where precision loss (float's 6-7 digit limit vs double's ~15) is the bigger practical risk in everyday arithmetic. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`int`** — whole numbers without decimals. [S1]
|
||||
- **`float`** — decimal numbers, ~6-7 significant decimal digits of precision, 4 bytes. [S1]
|
||||
- **`double`** — decimal numbers, ~15 significant decimal digits of precision, 8 bytes; recommended default for most calculations despite the extra memory cost. [S1]
|
||||
- **Scientific notation** — `e`/`E` means "times 10 to the power of" (e.g. `35e3` = 35 × 10³ = 35000), useful for writing very large/small numbers compactly. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic declarations: `int myNum = 1000;`, `float myNum = 5.75;`, `double myNum = 19.99;` each printed with `%d`/`%f`/`%lf` respectively. [S1]
|
||||
- Scientific notation usage: `float f1 = 35e3; double d1 = 12E4; printf("%f\n", f1); printf("%lf", d1);` — evaluates to 35000 and 120000 respectively. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **float보다 double을 기본으로 권장**: float가 메모리를 절반만 쓰지만, 대부분의 계산에는 정밀도가 더 높은 double을 쓰는 것이 더 안전하다는 점이 명시적으로 권고됨(메모리 절약보다 정밀도 손실 위험을 우선 고려). [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 과학적 표기법(35e3)으로 큰 수를 짧게 표현하는 것이 대규모 데이터나 과학 계산 코드에서 실전 활용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Scientific notation for compactly writing large floating-point numbers (C):
|
||||
```c
|
||||
float f1 = 35e3; // 35 * 10^3 = 35000
|
||||
double d1 = 12E4; // 12 * 10^4 = 120000
|
||||
printf("%f\n", f1);
|
||||
printf("%lf", d1);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types]], [[C Data Types Characters]], [[C Data Types Dec]]
|
||||
- **참조 맥락:** 숫자 타입 상세 — 문자 타입(Data Types Characters) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Numeric Data Types — https://www.w3schools.com/c/c_data_types_numbers.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Numeric Data Types" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-data-types-reallife
|
||||
title: "C Data Types Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["real-life data types", "total cost calculation", "C 데이터 타입 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "data-types", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Data Types Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
This example combines THREE distinct techniques from earlier chapters into one realistic calculation — `int`×`float` multiplication implicitly producing a `float` result (`total_cost`), the `%.2f` precision control from the Decimal Precision chapter, and a `char` currency symbol printed alongside — showing that real-world numeric code is rarely a single-type operation but a composition of the type/precision/character lessons taught separately. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Mixed-type arithmetic** — multiplying an `int` (`items`) by a `float` (`cost_per_item`) and storing the result in a `float` (`total_cost`). [S1]
|
||||
- **Precision-controlled currency output** — using `%.2f` to show exactly two decimal places for monetary values, paired with a `char` currency symbol. [S1]
|
||||
- **Calculate-then-print pattern reused** — the total is computed once and stored in a variable before being printed, consistent with the earlier Variables RealLife chapter's rectangle-area pattern. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Full calculation and display: `int items = 50; float cost_per_item = 9.99; float total_cost = items * cost_per_item; char currency = '$'; printf("Number of items: %d\n", items); printf("Cost per item: %.2f %c\n", cost_per_item, currency); printf("Total cost = %.2f %c\n", total_cost, currency);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 수량(int)×단가(float)로 총 비용을 계산하고 통화 기호(char)와 함께 소수점 둘째 자리까지 출력하는 이 예제 자체가 영수증/가격 계산 UI의 실전 활용 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Combining int, float, and char types with precision control for a currency calculation (C):
|
||||
```c
|
||||
int items = 50;
|
||||
float cost_per_item = 9.99;
|
||||
float total_cost = items * cost_per_item;
|
||||
char currency = '$';
|
||||
printf("Total cost = %.2f %c\n", total_cost, currency);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types Sizeof]], [[C Data Types Dec]], [[C Constants]]
|
||||
- **참조 맥락:** 데이터 타입 섹션 마지막 — 상수 및 저장 클래스(Constants & Storage) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Data Types Examples — https://www.w3schools.com/c/c_data_types_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Data Types Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-data-types-sizeof
|
||||
title: "C The sizeof Operator"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["sizeof operator", "%zu", "size_t", "C sizeof 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "sizeof", "memory"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_data_types_sizeof.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C The sizeof Operator]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`sizeof` doesn't return a plain `int` — it returns `size_t`, an unsigned integer type — so printing it with `%d` "might work on some computers" but is explicitly called out as unsafe/non-portable, meaning the correct specifier `%zu` isn't just a style preference but a genuine portability requirement for code that needs to run correctly across different systems. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`sizeof`** — an operator (not a function, syntactically) that returns the number of bytes a type or variable occupies in memory. [S1]
|
||||
- **`size_t`** — the unsigned integer type `sizeof` actually returns, requiring the `%zu` format specifier for safe/portable printing (not `%d`). [S1]
|
||||
- **Practical memory-usage reasoning** — a 1000-element `char` array (1 byte each) occupies exactly 1000 bytes (1 KB), directly connecting type size to real memory footprint. [S1]
|
||||
- **Motivation** — choosing the right data type for the right purpose saves memory and improves performance, especially in larger programs or memory-constrained environments. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic usage on variables: `int myInt; printf("%zu\n", sizeof(myInt));`. [S1]
|
||||
- Portability warning: using `%d` instead of `%zu` "might work on some computers" but `%zu` is "safer and more portable" since it matches `size_t`'s actual unsigned type. [S1]
|
||||
- Memory-footprint reasoning: "if you have an array of 1000 char values, it will occupy 1000 bytes (1 KB) of memory" — 1 byte per char × 1000 elements. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **%d 대신 %zu를 써야 하는 이유**: sizeof가 반환하는 size_t는 부호 없는 정수형이라, %d로 출력하면 일부 컴퓨터에서는 우연히 동작할 수 있어도 이식성이 떨어진다는 점이 명확히 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 1000개짜리 char 배열이 정확히 1KB를 차지한다는 계산이 메모리 제약 환경에서 타입 크기를 실전적으로 따져보는 대표 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Correctly printing sizeof() results using the %zu specifier, not %d (C):
|
||||
```c
|
||||
int myInt;
|
||||
float myFloat;
|
||||
printf("%zu\n", sizeof(myInt));
|
||||
printf("%zu\n", sizeof(myFloat));
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Data Types Extended]], [[C Data Types RealLife]], [[C Fixed Width Ints]]
|
||||
- **참조 맥락:** sizeof 연산자 — 데이터 타입 실전 예제(Data Types RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C The sizeof Operator — https://www.w3schools.com/c/c_data_types_sizeof.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C The sizeof Operator" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-date-time
|
||||
title: "C Date and Time"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["time.h", "struct tm", "strftime", "C 날짜와 시간"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "date-time", "time.h"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_date_time.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Date and Time]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`struct tm`'s year and month fields are BOTH offset in ways that will silently produce wrong output if you forget to correct them — `tm_year` counts years SINCE 1900 (so you must add 1900 to get the real year) and `tm_mon` is zero-indexed (0 = January, so you must add 1 for a human-readable month) — two unrelated offset conventions bundled into the same struct that both require manual correction before display. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`time(&var)` / `time(NULL)`** — retrieves the current time as a `time_t` value. [S1]
|
||||
- **`ctime(&time_t_value)`** — converts a raw `time_t` into a human-readable string (e.g. "Mon Jun 24 10:15:00 2025"). [S1]
|
||||
- **`localtime(&time_t_value)`** — converts a `time_t` into a `struct tm` POINTER, breaking the time into separate fields (year/month/day/hour/minute/second); accessed via `->` since it's a pointer, per the earlier Structs & Pointers rule. [S1]
|
||||
- **`tm_year` offset** — stores years SINCE 1900; must add 1900 for the actual calendar year. [S1]
|
||||
- **`tm_mon` offset** — zero-indexed (0=January, 11=December); must add 1 for the conventional 1-12 month number. [S1]
|
||||
- **`strftime(buffer, size, format, tm_ptr)`** — formats a `struct tm` into a custom string layout (e.g. `"%d-%m-%Y %H:%M:%S"`), writing into a caller-provided buffer. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Getting and printing the current time as a readable string: `time_t currentTime; time(¤tTime); printf("Current time: %s", ctime(¤tTime));`. [S1]
|
||||
- Breaking time into fields with the required offset corrections: `time_t now = time(NULL); struct tm *t = localtime(&now); printf("Year: %d\n", t->tm_year + 1900); printf("Month: %d\n", t->tm_mon + 1); printf("Day: %d\n", t->tm_mday);`. [S1]
|
||||
- Custom-formatted timestamp: `char buffer[100]; strftime(buffer, sizeof(buffer), "%d-%m-%Y %H:%M:%S", t); printf("Formatted time: %s\n", buffer);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **tm_year와 tm_mon의 오프셋 함정**: tm_year는 1900년 기준 경과 연수이므로 실제 연도를 얻으려면 1900을 더해야 하고, tm_mon은 0부터 시작(0=1월)하므로 실제 월을 얻으려면 1을 더해야 한다는 점이 각각 별개의 주의사항으로 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 로그 기록, 파일/메시지에 타임스탬프 추가, 실행 시간 측정, 난수 시드 설정 등이 날짜/시간 라이브러리의 대표 활용 목적으로 원문에 직접 나열됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Breaking the current time into fields with the mandatory offset corrections (C):
|
||||
```c
|
||||
#include <time.h>
|
||||
time_t now = time(NULL);
|
||||
struct tm *t = localtime(&now);
|
||||
printf("Year: %d\n", t->tm_year + 1900); // tm_year counts from 1900
|
||||
printf("Month: %d\n", t->tm_mon + 1); // tm_mon is 0-indexed
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C User Input]], [[C Structs Pointers]], [[C Random Numbers]], [[C Errors]]
|
||||
- **참조 맥락:** 사용자 입력 및 날짜 섹션 마지막 — 에러 및 디버깅(Errors & Debugging) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Date and Time — https://www.w3schools.com/c/c_date_time.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Date and Time" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: c-debugging
|
||||
title: "C Debugging"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["print debugging", "breakpoints", "debugging vs error handling", "C 디버깅"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "debugging"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_debugging.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Debugging]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The chapter's closing distinction reframes debugging and error handling as two DIFFERENT PHASES of the same concern, not competing techniques: debugging is about finding/fixing mistakes DURING DEVELOPMENT, while error handling is about gracefully responding to problems WHILE THE PROGRAM RUNS in production — meaning a well-built C program needs both, applied at different times, not one instead of the other. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Print debugging** — sprinkling `printf()` calls to trace how far execution gets before something goes wrong; if an expected message never prints, the crash happened before that line. [S1]
|
||||
- **Checking variable values** — printing intermediate results to catch LOGIC errors (e.g. expecting 15 but getting 5 reveals a wrong operator, not a crash). [S1]
|
||||
- **IDE debuggers** — breakpoints, line-by-line stepping, and variable-watching, available in IDEs like Visual Studio/Code::Blocks/VS Code; recommended as a step UP from `printf()` debugging once comfortable with the basics. [S1]
|
||||
- **Reading error messages literally** — the compiler/runtime often states exactly what's wrong and where (e.g. `expected ';' before 'printf'` → the fix is adding the missing semicolon). [S1]
|
||||
- **Defensive checks preventing crashes** — proactively checking conditions that are KNOWN to cause crashes (e.g. `if (y != 0)` before dividing, `if (index >= 0 && index < 3)` before array access) converts a crash into a graceful error message. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Print debugging locating a crash point: `printf("Before division\n"); int z = x / y; printf("After division\n");` — if "After division" never prints, the crash happened at the division. [S1]
|
||||
- Logic-error detection via variable printing: `int result = x - y; printf("Result: %d\n", result); // Result: 5 (expected 15 — wrong operator used)`. [S1]
|
||||
- Preventing a divide-by-zero crash with a defensive check: `if (y != 0) { int z = x / y; printf("Result: %d\n", z); } else { printf("Error: Division by zero!\n"); }`. [S1]
|
||||
- Preventing an out-of-bounds crash with a defensive check: `if (index >= 0 && index < 3) { printf("Value = %d\n", numbers[index]); } else { printf("Error: Index out of bounds!\n"); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **디버깅과 에러 처리는 서로 다른 단계**: 디버깅은 개발 중 버그를 찾고 고치는 활동이고, 에러 처리는 프로그램이 실제로 실행되는 중 문제에 대응하는 것이라는 점이 명확히 구분되며, 둘 다 필요하다는 점이 결론으로 제시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
0으로 나누기와 배열 범위 초과 접근이라는 두 가지 대표적 크래시 상황을 사전 조건 검사로 방지하는 방법이 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Preventing a division-by-zero crash with a defensive check instead of a printf-based fix (C):
|
||||
```c
|
||||
int x = 10;
|
||||
int y = 0;
|
||||
if (y != 0) {
|
||||
int z = x / y;
|
||||
printf("Result: %d\n", z);
|
||||
} else {
|
||||
printf("Error: Division by zero!\n");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Input Validation]], [[C Errors]], [[C Files]]
|
||||
- **참조 맥락:** 에러 및 디버깅 섹션 마지막 — 파일 입출력(Files) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Debugging — https://www.w3schools.com/c/c_debugging.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Debugging" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-do-while-loop
|
||||
title: "C Do/While Loop"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["do while", "at-least-once loop", "scanf input validation loop", "C do-while 반복문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "do-while"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_do_while_loop.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Do/While Loop]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The core difference from a regular `while` loop isn't cosmetic syntax — it's WHEN the condition is checked: `do/while` runs the body FIRST and evaluates the condition only AFTER, guaranteeing at least one execution even if the condition is false from the very start (`int i = 10; do {...} while (i < 5);` still runs once), which is exactly the opposite of the plain `while` loop's zero-iteration behavior shown in the previous chapter. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`do { ... } while (condition);`** — executes the block ONCE unconditionally, then checks the condition to decide whether to repeat. [S1]
|
||||
- **Guaranteed first execution** — unlike `while`, the body runs at least once even if the condition is false immediately. [S1]
|
||||
- **Use case: "at least once" behavior** — ideal for scenarios like showing a message or prompting for user input, where the action must happen before any condition can even be evaluated. [S1]
|
||||
- **Input-validation pattern** — repeatedly prompting via `scanf()` until the user provides a value that fails the loop condition (e.g. entering 0 or negative to stop). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Standard case (condition true at start): `int i = 0; do { printf("%d\n", i); i++; } while (i < 5);`. [S1]
|
||||
- Guaranteed-once case (condition false at start): `int i = 10; do { printf("i is %d\n", i); i++; } while (i < 5);` — still prints once despite `i < 5` being false immediately. [S1]
|
||||
- Practical input-validation loop: `int number; do { printf("Enter a positive number: "); scanf("%d", &number); } while (number > 0);` — keeps prompting until 0 or a negative number is entered. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **do/while은 조건과 무관하게 최소 1회 실행**: 일반 while 루프는 조건이 처음부터 거짓이면 아예 실행되지 않지만, do/while은 조건이 거짓이어도 반드시 한 번은 실행된다는 점이 직접 대비되어 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
사용자로부터 양수를 입력받되 0이나 음수가 입력될 때까지 반복해서 물어보는 입력 검증 루프가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
An input-validation loop that must prompt at least once before checking the exit condition (C):
|
||||
```c
|
||||
int number;
|
||||
do {
|
||||
printf("Enter a positive number: ");
|
||||
scanf("%d", &number);
|
||||
} while (number > 0);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C While Loop RealLife]], [[C For Loop]], [[C User Input]]
|
||||
- **참조 맥락:** while 루프의 변형 — for 루프(For Loop) 챕터로 이어짐, 사용자 입력(User Input) 챕터와 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Do/While Loop — https://www.w3schools.com/c/c_do_while_loop.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Do/While Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-enums
|
||||
title: "C Enumeration (enum)"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["enum keyword", "named constants", "C 열거형"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "enums"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_enums.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Enumeration (enum)]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Assigning an explicit value to just ONE enum item cascades forward — `enum Level { LOW = 5, MEDIUM, HIGH };` gives `MEDIUM` the value 6 and `HIGH` the value 7 automatically, without being written explicitly — meaning enum numbering isn't independently assigned per item by default; each unlabeled item simply continues incrementing from whatever the PRECEDING item's value was. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`enum`** — a type representing a group of named, unchangeable constants ("specifically listed" values). [S1]
|
||||
- **Default numbering** — the first item is 0, the second 1, and so on, unless overridden. [S1]
|
||||
- **Forward-cascading custom values** — setting one item's value shifts all SUBSEQUENT unlabeled items to continue counting up from it. [S1]
|
||||
- **Enum as an int under the hood** — printing an enum variable with `%d` shows its underlying integer value, enabling direct use in `switch` statements matched against those integers. [S1]
|
||||
- **`typedef` with enum** — eliminates needing to write `enum` before the type name every time a variable is declared, a pure readability/brevity improvement. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Default numbering: `enum Level { LOW, MEDIUM, HIGH }; enum Level myVar = MEDIUM; printf("%d", myVar); // 1`. [S1]
|
||||
- Fully custom values: `enum Level { LOW = 25, MEDIUM = 50, HIGH = 75 };`. [S1]
|
||||
- Cascading from one custom value: `enum Level { LOW = 5, MEDIUM, HIGH };` — MEDIUM becomes 6, HIGH becomes 7. [S1]
|
||||
- Enum used in a switch: `enum Level myVar = MEDIUM; switch (myVar) { case 1: ... case 2: ... case 3: ... }` (matching against LOW=1, MEDIUM=2, HIGH=3). [S1]
|
||||
- typedef shortcut: `typedef enum {MON, TUE, WED, THU, FRI, SAT, SUN} Day; Day today = WED;` instead of `enum Day today = WED;`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **하나의 값 지정이 이후 항목까지 연쇄적으로 영향**: LOW = 5로 지정하면 뒤따르는 MEDIUM, HIGH는 명시하지 않아도 자동으로 6, 7이 된다는 점이 명확히 확인됨 — 각 항목이 독립적으로 0부터 재시작하는 것이 아님. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
요일(Day)이나 월과 같이 절대 변하지 않는 값 집합에 enum을 사용하는 것이 실전 활용의 대표 사례로 원문에 직접 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Setting one enum value causes subsequent items to cascade forward from it (C):
|
||||
```c
|
||||
enum Level {
|
||||
LOW = 5,
|
||||
MEDIUM, // Now 6
|
||||
HIGH // Now 7
|
||||
};
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Structs Pointers]], [[C Switch]], [[C Unions]], [[C Typedef]]
|
||||
- **참조 맥락:** 열거형 — 유니온(Unions) 챕터로 이어짐, typedef 챕터와 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Enumeration (enum) — https://www.w3schools.com/c/c_enums.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Enumeration (enum)" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: c-error-handling
|
||||
title: "C Error Handling"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["perror strerror errno", "exit EXIT_FAILURE", "C 에러 처리"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "error-handling", "errno"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_error_handling.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Error Handling]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
C has NO try/catch mechanism at all — the source states this directly — meaning every error-handling technique in this chapter (checking for `NULL` returns, `perror()`, `strerror(errno)`, comparing `errno` to constants like `ENOENT`) is a WORKAROUND built from ordinary control flow (if-statements and return values), not a language feature, which is why disciplined manual NULL-checking after every risky operation is non-negotiable in C in a way it isn't in exception-based languages. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **No built-in exceptions** — C lacks try/catch; error handling relies on return values, global error codes (`errno`), and helper functions. [S1]
|
||||
- **NULL-return checking** — many functions (like `fopen()`) return `NULL` on failure; checking with `if (ptr == NULL)` is the primary detection mechanism. [S1]
|
||||
- **`perror(message)`** — prints a custom message plus a system-provided description of the last error. [S1]
|
||||
- **`errno` + `strerror(errno)`** — `errno` (from `<errno.h>`) holds the last failed operation's error code; `strerror()` converts it to a readable string. [S1]
|
||||
- **Named error constants** — `ENOENT` (no such file/directory), `EACCES` (permission denied), `ENOMEM` (out of memory), `EINVAL` (invalid argument) — allow branching on the SPECIFIC failure reason. [S1]
|
||||
- **`exit(code)`** — immediately terminates the program with a status code; `0`/`EXIT_SUCCESS` means success, non-zero/`EXIT_FAILURE` signals an error to the OS. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic NULL check: `FILE *fptr = fopen("nothing.txt", "r"); if (fptr == NULL) { printf("Error opening file.\n"); return 1; }`. [S1]
|
||||
- Detailed error via `perror()`: `perror("Error opening file"); // "Error opening file: No such file or directory"`. [S1]
|
||||
- Branching on a specific error code: `if (errno == ENOENT) { printf("The file was not found.\n"); } else { printf("Some other file error occurred.\n"); }`. [S1]
|
||||
- Exiting cleanly with readable status constants: `if (f == NULL) { perror("Could not open nothing.txt"); exit(EXIT_FAILURE); } return EXIT_SUCCESS;`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **C에는 try/catch가 없음**: 다른 언어와 달리 예외 처리 메커니즘이 아예 없고, 반환값·errno·perror()/strerror() 같은 도구를 조합해 직접 에러를 감지하고 대응해야 한다는 점이 명시적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
존재하지 않는 파일(nothing.txt)을 열려는 시도가 실패하는 상황을 NULL 체크, perror(), strerror(errno), errno 비교, exit() 등 다섯 가지 방식으로 반복 제시하며 각 기법의 실전 활용을 직접 보여줌. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Detecting a specific error condition via errno and reporting it with a custom message (C):
|
||||
```c
|
||||
#include <errno.h>
|
||||
FILE *f = fopen("nothing.txt", "r");
|
||||
if (f == NULL) {
|
||||
if (errno == ENOENT) {
|
||||
printf("The file was not found.\n");
|
||||
} else {
|
||||
printf("Some other file error occurred.\n");
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Errors]], [[C Null]], [[C Input Validation]]
|
||||
- **참조 맥락:** 에러 처리 — 입력 검증(Input Validation) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Error Handling — https://www.w3schools.com/c/c_error_handling.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Error Handling" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-errors
|
||||
title: "C Errors"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["compile-time vs runtime errors", "use-after-free", "C 에러"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "errors"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_errors.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Errors]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The three runtime error examples (divide-by-zero, out-of-bounds array access, use-after-free) all share a common trait the source doesn't state explicitly but demonstrates through selection: NONE of them are caught by the compiler — all three compile cleanly and only misbehave when actually EXECUTED — meaning C's compile-time checking is fundamentally limited to syntax/type issues, while logic and memory-safety issues are entirely the programmer's responsibility to prevent at runtime. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Compile-time errors** — prevent the program from compiling at all; e.g. missing semicolon, undeclared variable, mismatched types (assigning a string literal to an `int`). [S1]
|
||||
- **Runtime errors** — the program compiles successfully but crashes or misbehaves when RUN; e.g. division by zero, out-of-bounds array access, using memory after `free()`. [S1]
|
||||
- **Use-after-free** — reading `*ptr` after `free(ptr)` is explicitly labeled "undefined behavior," not a guaranteed crash — meaning it might appear to work sometimes, making it a particularly dangerous class of bug. [S1]
|
||||
- **Good habits** — always initialize variables, use meaningful names, keep indentation clean, keep functions short/focused, verify loop/condition behavior, and read error messages carefully (they often pinpoint the exact problem). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Missing semicolon (compile-time): `int x = 5 printf("%d", x);` → `error: expected ',' or ';' before 'printf'`. [S1]
|
||||
- Type mismatch (compile-time): `int x = "Hello";` → `error: initialization makes integer from pointer without a cast`. [S1]
|
||||
- Use-after-free (runtime, undefined behavior): `int* ptr = malloc(sizeof(int)); *ptr = 10; free(ptr); printf("%d\n", *ptr); // accessing freed memory`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **해제된 메모리 접근은 "미정의 동작"**: free() 이후 포인터를 읽는 것이 항상 크래시로 이어지는 것이 아니라 "undefined behavior"로 명시되어, 우연히 정상 동작하는 것처럼 보일 수도 있어 더 위험하다는 점이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 컴파일 타임 에러 3종과 런타임 에러 3종을 나란히 대비시킨 것이 두 에러 범주의 근본적 차이를 이해하는 실전 학습 자료로 활용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Using memory after it's been freed — compiles fine, but is undefined behavior at runtime (C):
|
||||
```c
|
||||
int* ptr = malloc(sizeof(int));
|
||||
*ptr = 10;
|
||||
free(ptr);
|
||||
printf("%d\n", *ptr); // Undefined behavior - accessing memory that was freed
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Date Time]], [[C Memory Deallocate]], [[C Error Handling]]
|
||||
- **참조 맥락:** 에러 섹션 첫 챕터 — 에러 처리(Error Handling) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Errors — https://www.w3schools.com/c/c_errors.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Errors" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-files
|
||||
title: "C Files"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["fopen fclose", "file mode", "C 파일 핸들링"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "files", "fopen"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_files.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Files]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Opening a file in write mode (`"w"`) doubles as CREATING it — if `"filename.txt"` doesn't already exist, `fopen(filename, "w")` silently creates a brand new empty file instead of failing, meaning "open for writing" and "create if missing" are the same operation in C's file model, not two separate steps a program must handle. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`FILE *fptr`** — a pointer to the special `FILE` data type, required to work with any file operations. [S1]
|
||||
- **`fopen(filename, mode)`** — opens (or creates) a file; returns a `FILE*` pointer used for all subsequent operations on it. [S1]
|
||||
- **Three basic modes** — `"w"` (write; creates the file if it doesn't exist), `"a"` (append new data), `"r"` (read). [S1]
|
||||
- **`fclose(fptr)`** — closes the file, ensuring changes are saved, freeing it for other programs, and releasing unnecessary memory. [S1]
|
||||
- **Absolute paths need escaped backslashes** — Windows paths like `C:\directoryname\filename.txt` must be written `"C:\\directoryname\\filename.txt"` in C string literals, per the earlier Strings Escape chapter's `\\` rule. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Creating (or opening for writing) a file: `FILE *fptr; fptr = fopen("filename.txt", "w"); fclose(fptr);`. [S1]
|
||||
- Creating a file at an absolute Windows path with escaped backslashes: `fptr = fopen("C:\\directoryname\\filename.txt", "w");`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **"w" 모드는 쓰기와 생성을 동시에 수행**: 파일이 존재하지 않아도 fopen(filename, "w")가 실패하지 않고 새 파일을 만들어준다는 점이 명시적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — fclose()를 반드시 호출해 변경사항 저장/메모리 정리/다른 프로그램의 파일 사용을 보장하는 것이 실전 파일 작업의 필수 관행으로 강조된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Opening (and implicitly creating) a file, then closing it (C):
|
||||
```c
|
||||
FILE *fptr;
|
||||
// Create a file (or open it for writing)
|
||||
fptr = fopen("filename.txt", "w");
|
||||
// Close the file
|
||||
fclose(fptr);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Debugging]], [[C Strings Esc]], [[C Files Read]]
|
||||
- **참조 맥락:** 파일 섹션 첫 챕터 — 파일 읽기(Files Read) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Files — https://www.w3schools.com/c/c_files.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Files" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: c-files-read
|
||||
title: "C Read Files"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["fgets file reading", "read multiple lines", "C 파일 읽기"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "files", "fgets"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_files_read.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Read Files]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A single `fgets()` call only reads ONE LINE, not the whole file — the source's own example proves it by showing "filename.txt" has two lines but only "Hello World!" prints from one call, and the fix (wrapping `fgets()` in a `while` loop) works because `fgets()` naturally returns falsy/NULL once it hits end-of-file, making the loop condition double as the "keep reading until there's nothing left" check with no separate end-of-file test needed. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`fopen(filename, "r")`** — opens a file specifically for reading. [S1]
|
||||
- **`fgets(buffer, maxSize, fptr)`** — reads UP TO `maxSize` characters (or until a newline) from `fptr` into `buffer`; reads only ONE line per call. [S1]
|
||||
- **`while (fgets(...))` pattern** — repeatedly calling `fgets()` inside a `while` loop reads the ENTIRE file line by line; the loop naturally stops once `fgets()` reaches end-of-file (returns a falsy value). [S1]
|
||||
- **NULL-check for missing files** — `fopen()` returns `NULL` if the file doesn't exist for reading; checking `if (fptr == NULL)` before use prevents crashes. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Reading only the FIRST line (a common early mistake): `FILE *fptr = fopen("filename.txt", "r"); char myString[100]; fgets(myString, 100, fptr); printf("%s", myString); // only "Hello World!", missing the second line`. [S1]
|
||||
- Reading the ENTIRE file with a while loop: `while(fgets(myString, 100, fptr)) { printf("%s", myString); } // prints both "Hello World!" and "Hi everybody!"`. [S1]
|
||||
- Combining NULL-checking with the full-file read pattern: `if(fptr != NULL) { while(fgets(myString, 100, fptr)) { printf("%s", myString); } } else { printf("Not able to open the file."); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **fgets 한 번 호출로는 첫 줄만 읽힘**: 파일에 여러 줄이 있어도 fgets()를 한 번만 호출하면 첫 줄만 읽힌다는 점이 직접 비교 예제로 증명되며, 전체 파일을 읽으려면 while 루프로 감싸야 한다는 해법이 제시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
파일이 존재하지 않을 경우 NULL을 체크해 "파일을 열 수 없습니다" 메시지를 출력하는 안전한 파일 읽기 패턴이 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Safely reading an entire file line by line, with a NULL check for missing files (C):
|
||||
```c
|
||||
FILE *fptr;
|
||||
fptr = fopen("filename.txt", "r");
|
||||
char myString[100];
|
||||
if (fptr != NULL) {
|
||||
while (fgets(myString, 100, fptr)) {
|
||||
printf("%s", myString);
|
||||
}
|
||||
} else {
|
||||
printf("Not able to open the file.");
|
||||
}
|
||||
fclose(fptr);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Files]], [[C User Input]], [[C Files Write]]
|
||||
- **참조 맥락:** 파일 읽기 — 파일 쓰기(Files Write) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Read Files — https://www.w3schools.com/c/c_files_read.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Read Files" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-files-write
|
||||
title: "C Write To Files"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["fprintf", "write vs append mode", "C 파일 쓰기"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "files", "fprintf"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_files_write.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Write To Files]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Opening an EXISTING file in `"w"` mode silently DESTROYS its entire prior content the moment `fopen()` succeeds — not when you write, just from opening — the source explicitly warns "you might accidentally erase existing content," meaning `"w"` mode is fundamentally destructive/overwrite-only, and `"a"` (append) exists as the ONLY mode that preserves existing content while adding to it. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`fprintf(fptr, text)`** — writes formatted text to the file pointed to by `fptr`, the file-writing analog of `printf()`. [S1]
|
||||
- **`"w"` mode is destructive** — opening an existing file for writing immediately discards its old content, even before any `fprintf()` call. [S1]
|
||||
- **`"a"` (append) mode** — adds new content to the END of the file WITHOUT deleting what's already there. [S1]
|
||||
- **`"a"` also creates missing files** — just like `"w"`, appending to a non-existent file creates it fresh with the appended content as its initial content. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Writing (and overwriting) content: `fptr = fopen("filename.txt", "w"); fprintf(fptr, "Some text"); fclose(fptr);` — then reopening with `"w"` again and writing `"Hello World!"` COMPLETELY replaces "Some text". [S1]
|
||||
- Appending without erasing prior content: `fptr = fopen("filename.txt", "a"); fprintf(fptr, "\nHi everybody!"); fclose(fptr);` — preserves whatever was already in the file. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **"w" 모드는 열자마자 기존 내용을 지움**: 이미 존재하는 파일을 "w" 모드로 열면 새 내용을 쓰기 전에 이미 기존 내용이 사라진다는 점이 명시적으로 경고되며, 실수로 기존 데이터를 날릴 수 있다는 주의사항이 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
"Some text"를 쓴 뒤 같은 파일을 다시 "w" 모드로 열어 "Hello World!"로 덮어쓰는 예제가 기존 내용이 완전히 사라지는 것을 직접 보여주는 실전 경고 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Appending to a file without erasing its existing content (C):
|
||||
```c
|
||||
FILE *fptr;
|
||||
fptr = fopen("filename.txt", "a"); // append mode preserves existing content
|
||||
fprintf(fptr, "\nHi everybody!");
|
||||
fclose(fptr);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Files Read]], [[C Files]], [[C Type Conversion]]
|
||||
- **참조 맥락:** 파일 섹션 마지막 — 타입 변환 및 매크로(Type Conversion & Macros) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Write To Files — https://www.w3schools.com/c/c_files_write.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Write To Files" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-fixed-width-ints
|
||||
title: "C Fixed Width Integers"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["stdint.h", "int32_t uint8_t", "C 고정폭 정수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "fixed-width-integers", "stdint"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_fixed_width_ints.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Fixed Width Integers]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The battery-level example makes the case concrete: since a percentage is always 0-100, using a plain `int` (likely 4 bytes) instead of `uint8_t` (exactly 1 byte) wastes 3 bytes per value for NO benefit — fixed-width types aren't just about portability, they're a deliberate memory-fit-to-range decision that a generic `int` habit obscures. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **The portability problem** — `int`, `short`, `long` sizes vary by system/compiler (e.g. `int` might be 2 bytes on one system, 4 on another). [S1]
|
||||
- **`<stdint.h>` fixed-width types** — `int8_t`/`uint8_t` (1 byte), `int16_t`/`uint16_t` (2 bytes), `int32_t`/`uint32_t` (4 bytes), `int64_t`/`uint64_t` (8 bytes) — guaranteed identical size on every system. [S1]
|
||||
- **`u` prefix meaning** — unsigned; doubles the maximum positive range compared to the signed version, at the cost of no negative values. [S1]
|
||||
- **When they matter** — embedded/microcontroller systems, file formats requiring exact byte layouts, and network data exchange needing consistent results across machines. [S1]
|
||||
- **When they don't matter** — for most everyday programs, a normal `int` is sufficient; fixed-width types are a deliberate choice for specific constraints, not a default habit. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Declaring across all four sizes: `int8_t a = 100; int16_t b = 30000; int32_t c = 2000000; int64_t d = 9000000000;` printed with `%d`/`%d`/`%d`/`%lld` respectively. [S1]
|
||||
- Battery-level real-life example: `uint8_t battery = 87; printf("Battery level is %u out of 100\n", battery);` — a value naturally bounded 0-255 fits exactly in 1 byte. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **고정폭 타입은 일상 프로그래밍에는 불필요**: 대부분의 프로그램에서는 일반 int로 충분하며, 고정폭 타입은 임베디드 시스템/파일 포맷/네트워크 통신처럼 정확한 크기가 중요한 특수 상황에서만 필요하다는 점이 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
배터리 잔량(0-100%)처럼 값의 범위가 명확히 제한된 경우 uint8_t를 사용해 메모리를 절약하는 것이 실전 임베디드 프로그래밍의 대표 활용 사례로 원문에 직접 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Using a 1-byte fixed-width type for a value with a known bounded range (C):
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
int main() {
|
||||
uint8_t battery = 87; // battery level percentage, fits in 1 byte
|
||||
printf("Battery level is %u out of 100\n", battery);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Storage Classes]], [[C Data Types Extended]], [[C Operators]]
|
||||
- **참조 맥락:** 상수 및 저장 클래스 섹션 마지막 — 연산자(Operators) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Fixed Width Integers — https://www.w3schools.com/c/c_fixed_width_ints.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Fixed Width Integers" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-for-loop
|
||||
title: "C For Loop"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["for statement", "three-expression loop", "C for 반복문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "for-loop"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_for_loop.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C For Loop]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source frames the `for` vs `while` choice as a matter of KNOWING the iteration count in advance — "when you know exactly how many times you want to loop... use the for loop instead of a while loop" — meaning `for` isn't a functionally different tool from `while` (a `for` loop can always be rewritten as a `while`), it's a structural convention that bundles initialization, condition, and increment into one line specifically for the fixed-count use case. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`for (expr1; expr2; expr3) { ... }`** — expr1 runs once before the loop starts; expr2 is the continuation condition checked each iteration; expr3 runs after each iteration's body. [S1]
|
||||
- **Fixed-count use case** — the recommended tool when the number of iterations is known ahead of time, unlike `while`'s open-ended condition-driven repetition. [S1]
|
||||
- **Flexible step expressions** — expr3 isn't limited to `++`; any increment/decrement/step size works (`i = i + 2`, `i--`, etc.). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic counting: `int i; for (i = 0; i < 5; i++) { printf("%d\n", i); }` — prints 0 to 4. [S1]
|
||||
- Custom step size for evens: `int i; for (i = 0; i <= 10; i = i + 2) { printf("%d\n", i); }`. [S1]
|
||||
- Accumulating a sum across iterations: `int sum = 0; int i; for (i = 1; i <= 5; i++) { sum = sum + i; } printf("Sum is %d", sum);`. [S1]
|
||||
- Countdown via decrement: `int i; for (i = 5; i > 0; i--) { printf("%d\n", i); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
1부터 5까지의 합을 for 루프로 누적 계산하는 예제(sum = sum + i)가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Accumulating a running total across for-loop iterations (C):
|
||||
```c
|
||||
int sum = 0;
|
||||
int i;
|
||||
for (i = 1; i <= 5; i++) {
|
||||
sum = sum + i;
|
||||
}
|
||||
printf("Sum is %d", sum);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Do While Loop]], [[C For Loop Nested]], [[C For Loop RealLife]]
|
||||
- **참조 맥락:** for 루프 — 중첩 for 루프(For Loop Nested) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C For Loop — https://www.w3schools.com/c/c_for_loop.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C For Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-for-loop-nested
|
||||
title: "C Nested Loops"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["inner outer loop", "multiplication table", "C 중첩 반복문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "nested-loops"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_for_loop_nested.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Nested Loops]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The inner loop's total execution count MULTIPLIES with the outer loop's — the source explicitly annotates a 2-iteration outer loop paired with a 3-iteration inner loop as running the inner body "6 times (2 * 3)," not 2+3=5 — meaning nested loop cost grows multiplicatively, not additively, which is directly why nested loops are the natural fit for 2D structures like tables and matrices where total cells = rows × columns. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Nested loop** — a loop placed entirely inside another loop's body; the inner loop runs to completion once for EVERY single iteration of the outer loop. [S1]
|
||||
- **Multiplicative execution count** — total inner-body executions = (outer iterations) × (inner iterations per outer iteration), not their sum. [S1]
|
||||
- **Natural fit for 2D data** — tables, matrices, and multi-dimensional structures map naturally onto outer-loop-as-rows, inner-loop-as-columns. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic nesting with explicit iteration-count annotation: `for (i = 1; i <= 2; ++i) { printf("Outer: %d\n", i); for (j = 1; j <= 3; ++j) { printf(" Inner: %d\n", j); } }` — outer runs 2 times, inner runs 6 times total (2×3). [S1]
|
||||
- Multiplication table via nested loops: `for (i = 1; i <= 3; i++) { for (j = 1; j <= 3; j++) { printf("%d ", i * j); } printf("\n"); }` — produces a 3×3 grid: `1 2 3 / 2 4 6 / 3 6 9`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **중첩 루프의 실행 횟수는 곱셈**: 바깥 루프 2회 × 안쪽 루프 3회 = 안쪽 코드 총 6회 실행이라는 점이 원문에서 직접 명시되어, 덧셈이 아닌 곱셈 관계임이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
3x3 구구단표를 중첩 for 루프로 출력하는 예제가 원문에서 직접 실전 활용 사례로 제시되며, 표/행렬 같은 2차원 데이터 구조에 중첩 루프가 자연스럽게 맞는다는 점이 강조됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A multiplication table built from two nested for loops (C):
|
||||
```c
|
||||
int i, j;
|
||||
for (i = 1; i <= 3; i++) {
|
||||
for (j = 1; j <= 3; j++) {
|
||||
printf("%d ", i * j);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
// 1 2 3
|
||||
// 2 4 6
|
||||
// 3 6 9
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C For Loop]], [[C For Loop RealLife]], [[C Arrays Multi]]
|
||||
- **참조 맥락:** 중첩 for 루프 — for 루프 실전 예제(For Loop RealLife) 챕터로 이어짐, 다차원 배열(Arrays Multi) 챕터와 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Nested Loops — https://www.w3schools.com/c/c_for_loop_nested.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Nested Loops" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-for-loop-reallife
|
||||
title: "C For Loop Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["powers of 2", "multiplication table generator", "C for 루프 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "for-loop", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_for_loop_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C For Loop Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The powers-of-2 example (`for (i = 2; i <= 512; i *= 2)`) shows the third `for` expression isn't limited to addition or subtraction — MULTIPLICATIVE stepping works identically, meaning the "increment expression" slot in a for loop is really just "any expression that changes the loop variable," and the loop condition (`i <= 512`) naturally still governs when it stops regardless of HOW the variable changes each time. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Additive stepping by an arbitrary amount** — `i += 10` steps by tens; not restricted to `i++`/`i--`. [S1]
|
||||
- **Multiplicative stepping** — `i *= 2` doubles the value each iteration, producing powers of 2 rather than an arithmetic sequence. [S1]
|
||||
- **Parameterized multiplication table** — using a variable (`number`) instead of a hardcoded value lets the SAME loop generate any number's table. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Counting by tens: `for (i = 0; i <= 100; i += 10) { printf("%d\n", i); }`. [S1]
|
||||
- Odd numbers only: `for (i = 1; i < 10; i = i + 2) { printf("%d\n", i); }`. [S1]
|
||||
- Powers of 2 via multiplicative stepping: `for (i = 2; i <= 512; i *= 2) { printf("%d\n", i); }` — 2, 4, 8, 16, ..., 512. [S1]
|
||||
- Parameterized multiplication table: `int number = 2; int i; for (i = 1; i <= 10; i++) { printf("%d x %d = %d\n", number, i, number * i); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **증가식은 곱셈도 가능**: for 루프의 세 번째 표현식이 i++나 i+=N 뿐 아니라 i *= 2처럼 곱셈으로도 구성될 수 있다는 점이 확인되며, 2의 거듭제곱 수열 생성에 활용됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
2의 거듭제곱을 512까지 출력하는 예제와, 임의의 숫자(number 변수)에 대한 구구단표를 생성하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Multiplicative stepping in a for loop to generate powers of 2 (C):
|
||||
```c
|
||||
for (i = 2; i <= 512; i *= 2) {
|
||||
printf("%d\n", i);
|
||||
}
|
||||
// 2, 4, 8, 16, 32, 64, 128, 256, 512
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C For Loop Nested]], [[C Break Continue]]
|
||||
- **참조 맥락:** for 루프 실전 예제 — break/continue 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C For Loop Examples — https://www.w3schools.com/c/c_for_loop_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C For Loop Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
id: c-functions
|
||||
title: "C Functions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["void function", "function call", "C 함수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Functions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source reveals that `main()` and `printf()` — the two things every C beginner types on day one — are ALREADY functions, meaning the concept being "introduced" in this chapter isn't new at all; the learner has been using functions the entire tutorial without a name for it, and this chapter is really just formalizing vocabulary for a pattern already internalized. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Function** — a block of code that only runs when explicitly CALLED, not automatically at declaration time. [S1]
|
||||
- **`void` return type** — indicates the function returns no value (covered in more depth in the Parameters chapter). [S1]
|
||||
- **Declaration vs. execution timing** — declaring a function only "saves it for later use"; nothing inside runs until it's called. [S1]
|
||||
- **Repeatable calls** — the same function can be called multiple times, each execution independent. [S1]
|
||||
- **Code reuse motivation** — "define the code once, and use it many times" is the core justification for functions. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Calling the same function three times: `void myFunction() { printf("I just got executed!"); } int main() { myFunction(); myFunction(); myFunction(); return 0; }` — prints the message three times. [S1]
|
||||
- A function performing a fixed calculation: `void calculateSum() { int x = 5; int y = 10; int sum = x + y; printf("The sum of x + y is: %d", sum); }` — explicitly noted as LIMITED since x/y are hardcoded, motivating the next chapter's parameters. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — main()과 printf() 자체가 이미 함수라는 사실을 상기시키는 것이 이 챕터의 핵심 실전 통찰이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Calling the same function multiple times (C):
|
||||
```c
|
||||
void myFunction() {
|
||||
printf("I just got executed!");
|
||||
}
|
||||
int main() {
|
||||
myFunction();
|
||||
myFunction();
|
||||
myFunction();
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory RealLife]], [[C Functions Decl]]
|
||||
- **참조 맥락:** 함수 섹션 첫 챕터 — 함수 선언과 정의(Functions Decl) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Functions — https://www.w3schools.com/c/c_functions.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: c-functions-callback
|
||||
title: "C Callback Functions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["callback pattern", "qsort callback", "C 콜백 함수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "callbacks", "qsort"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_callback.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Callback Functions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`qsort()` — a real C standard library function, not a toy example — proves that callbacks aren't merely a teaching device but the actual mechanism the STANDARD LIBRARY itself relies on: `qsort()` has no idea how to compare YOUR specific data, so it delegates that decision entirely to a `compare()` function you supply, meaning the library's generic sorting algorithm and your data-specific comparison logic stay completely decoupled. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Callback function** — a function passed AS AN ARGUMENT to another function, which then calls it back whenever needed; implemented in C via function pointers. [S1]
|
||||
- **Decoupling logic from control flow** — the RECEIVING function (`runCallback`, `calculate`, `greet`) doesn't need to know the callback's name in advance; it just needs a matching function-pointer type. [S1]
|
||||
- **Parameter-matching requirement** — a callback with parameters requires the function pointer TYPE in the receiving function's signature to match exactly (`void (*callback)(int, int)`). [S1]
|
||||
- **Real standard-library usage: `qsort()`** — from `<stdlib.h>`; you supply a `compare()` function, and `qsort()` calls it internally as many times as needed while sorting. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic callback with before/after wrapping: `void runCallback(void (*callback)()) { printf("Before calling the callback...\n"); callback(); printf("After calling the callback.\n"); } runCallback(sayHello);`. [S1]
|
||||
- Callback with parameters: `void calculate(void (*callback)(int, int), int x, int y) { callback(x, y); } calculate(addNumbers, 5, 3);`. [S1]
|
||||
- Real-world `qsort()` usage with a user-supplied comparator: `int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } qsort(numbers, size, sizeof(int), compare);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
표준 라이브러리의 qsort() 함수가 사용자 정의 compare() 콜백을 받아 정렬 기준을 위임받는 것이 콜백 패턴의 실제 실전 활용 사례로 원문에 직접 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Using a user-supplied comparison callback with the standard library's qsort() (C):
|
||||
```c
|
||||
#include <stdlib.h>
|
||||
int compare(const void *a, const void *b) {
|
||||
return (*(int*)a - *(int*)b);
|
||||
}
|
||||
int main() {
|
||||
int numbers[] = { 5, 2, 9, 1, 7 };
|
||||
int size = sizeof(numbers) / sizeof(numbers[0]);
|
||||
qsort(numbers, size, sizeof(int), compare);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Pointers]], [[C Functions Inline]], [[C Scope]]
|
||||
- **참조 맥락:** 콜백 함수 — 인라인 함수(Functions Inline) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Callback Functions — https://www.w3schools.com/c/c_functions_callback.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Callback Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
id: c-functions-decl
|
||||
title: "C Function Declaration and Definition"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["function prototype", "forward declaration", "C 함수 선언과 정의"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "function-declaration"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_decl.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Function Declaration and Definition]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Separating a function's DECLARATION (name/return-type/parameters) from its DEFINITION (actual body) is what allows `main()` to call a function that's physically written BELOW it in the source file — without a forward declaration above `main()`, the compiler would encounter the function call before ever having seen what that function even looks like, since C reads files top to bottom. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Declaration** — the function's name, return type, and parameters ONLY, ending in a semicolon (`void myFunction();`), with no body. [S1]
|
||||
- **Definition** — the function's actual body/implementation. [S1]
|
||||
- **Recommended file layout** — declarations placed ABOVE `main()`, definitions placed BELOW `main()`, for organization and readability. [S1]
|
||||
- **Enables forward reference** — a function can be called from `main()` even though its full definition appears later in the file, as long as its declaration appeared earlier. [S1]
|
||||
- **Functions calling other functions** — as long as both are DECLARED first, one function's body can call another function that's defined elsewhere in the file. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Declaration-above, definition-below pattern: `void myFunction(); int main() { myFunction(); return 0; } void myFunction() { printf("I just got executed!"); }`. [S1]
|
||||
- Same pattern with parameters and a return value: `int myFunction(int x, int y); int main() { int result = myFunction(5, 3); ... } int myFunction(int x, int y) { return x + y; }`. [S1]
|
||||
- One function calling another, both pre-declared: `void myFunction(); void myOtherFunction(); int main() { myFunction(); return 0; } void myFunction() { printf("Some text in myFunction\n"); myOtherFunction(); } void myOtherFunction() { printf("Hey! Some text in myOtherFunction\n"); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 함수 선언을 main() 위에, 정의를 아래에 두는 구조가 대부분의 C 프로그램에서 표준적으로 쓰이는 코드 조직 방식이라고 원문에 명시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Declaring functions above main() and defining them below, allowing one to call the other (C):
|
||||
```c
|
||||
// Function declarations
|
||||
void myFunction();
|
||||
void myOtherFunction();
|
||||
|
||||
int main() {
|
||||
myFunction();
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Function definitions
|
||||
void myFunction() {
|
||||
printf("Some text in myFunction\n");
|
||||
myOtherFunction(); // calling another function
|
||||
}
|
||||
void myOtherFunction() {
|
||||
printf("Hey! Some text in myOtherFunction\n");
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions]], [[C Functions Parameters]]
|
||||
- **참조 맥락:** 함수 선언과 정의 — 함수 매개변수(Functions Parameters) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Function Declaration and Definition — https://www.w3schools.com/c/c_functions_decl.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Function Declaration and Definition" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-functions-inline
|
||||
title: "C Inline Function"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["inline keyword", "code bloat", "C 인라인 함수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "inline"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_inline.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Inline Function]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`inline` is merely a SUGGESTION, not a command — the compiler decides whether to actually inline the function regardless of the keyword, and the source explicitly warns that overusing it causes "code bloat" (larger, sometimes SLOWER programs) precisely because inlining trades a tiny call-overhead savings for duplicated code at every call site, a trade that only pays off for small, frequently-called functions. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`inline` keyword** — a hint asking the compiler to paste the function's code directly at each call site instead of jumping to a separate function call. [S1]
|
||||
- **Purely a performance hint** — behaves functionally identically to a regular function; the ONLY potential difference is compiled performance/size, never program logic. [S1]
|
||||
- **Best suited for small, frequently-called functions** — the call-overhead savings only outweighs code duplication when the function body is tiny and called often. [S1]
|
||||
- **When to avoid inline** — large functions (bloats the binary), recursive functions (can't sensibly be pasted infinitely), rarely-called functions (no meaningful benefit). [S1]
|
||||
- **Code bloat** — the risk of overusing `inline`: too many inlined functions make the program BIGGER and can even make it SLOWER overall, the opposite of the intended optimization. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Regular vs inline version of the same function, functionally identical: `int square(int x) { return x * x; }` versus `inline int square(int x) { return x * x; }`. [S1]
|
||||
- Compiler potentially replacing a call with its literal computation: `inline int add(int a, int b) { return a + b; } printf("%d", add(5, 3));` — the compiler MIGHT replace `add(5, 3)` directly with `5 + 3`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **inline은 강제가 아니라 힌트**: inline 키워드를 붙여도 실제로 인라인 처리할지는 컴파일러가 최종 결정하며, 너무 많이 사용하면 오히려 프로그램이 더 커지고 느려지는 "코드 블로트" 문제가 생길 수 있다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 튜토리얼 자체는 이후에도 계속 일반 함수(regular function)를 사용하겠다고 명시하며, inline은 초보자가 자주 쓸 필요는 없다고 밝힘. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A small, frequently-called function marked inline as a performance hint (C):
|
||||
```c
|
||||
inline int add(int a, int b) {
|
||||
return a + b;
|
||||
}
|
||||
int main() {
|
||||
printf("%d", add(5, 3)); // compiler may replace this with 5 + 3 directly
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Callback]], [[C Scope]]
|
||||
- **참조 맥락:** 함수 섹션 마지막 — 스코프(Scope) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Inline Function — https://www.w3schools.com/c/c_functions_inline.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Inline Function" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: c-functions-parameters
|
||||
title: "C Function Parameters"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["parameters vs arguments", "return values", "C 함수 매개변수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "parameters", "return-values"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_parameters.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Function Parameters]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Passing an array to a function only requires the ARRAY NAME at the call site (`myFunction(myNumbers)`), but the function's own parameter declaration must still spell out the full array type (`int myNumbers[5]`) — an asymmetry that follows directly from the earlier Pointers-and-Arrays insight that an array name is already a pointer to its first element, so the "argument" being passed really is just that one address, while the parameter declaration exists purely to tell the function how to interpret what's at that address. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Parameter vs. argument** — a parameter is the variable name INSIDE the function signature; an argument is the actual value passed at the CALL site (e.g. `name` is the parameter, `"Liam"` is the argument). [S1]
|
||||
- **Multiple parameters** — comma-separated in the signature; the call must supply the SAME NUMBER of arguments, IN THE SAME ORDER. [S1]
|
||||
- **Passing arrays** — call site uses just the array name; the function signature still needs the full array declaration (`int myNumbers[5]`). [S1]
|
||||
- **Return values via a real return type** — replacing `void` with a type (e.g. `int`) plus a `return` statement lets the function hand back a computed value instead of just performing an action. [S1]
|
||||
- **Storing results in arrays** — when many result variables would otherwise be needed, storing each function call's result into an array element keeps the code manageable. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Single string parameter reused across calls: `void myFunction(char name[]) { printf("Hello %s\n", name); } myFunction("Liam"); myFunction("Jenny");`. [S1]
|
||||
- Passing an array (name-only at call site, full type in signature): `void myFunction(int myNumbers[5]) { for (int i = 0; i < 5; i++) { printf("%d\n", myNumbers[i]); } } int myNumbers[5] = {10,20,30,40,50}; myFunction(myNumbers);`. [S1]
|
||||
- Returning a value instead of void: `int myFunction(int x, int y) { return x + y; } int result = myFunction(5, 3); // 8`. [S1]
|
||||
- Storing multiple call results into an array: `resultArr[0] = calculateSum(5, 3); resultArr[1] = calculateSum(8, 2); ...`. [S1]
|
||||
- Real-life Fahrenheit-to-Celsius conversion: `float toCelsius(float fahrenheit) { return (5.0 / 9.0) * (fahrenheit - 32.0); }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **인자 개수와 순서는 반드시 일치해야 함**: 여러 매개변수를 사용할 때 함수 호출의 인자 개수가 매개변수 개수와 같아야 하고 순서도 동일해야 한다는 점이 명시적으로 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
화씨를 섭씨로 변환하는 toCelsius() 함수가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A real-life function converting Fahrenheit to Celsius, returning a computed value (C):
|
||||
```c
|
||||
float toCelsius(float fahrenheit) {
|
||||
return (5.0 / 9.0) * (fahrenheit - 32.0);
|
||||
}
|
||||
int main() {
|
||||
float f_value = 98.8;
|
||||
float result = toCelsius(f_value);
|
||||
printf("Convert Fahrenheit to Celsius: %.2f\n", result);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Decl]], [[C Pointers Arrays]], [[C Functions Recursion]]
|
||||
- **참조 맥락:** 함수 매개변수와 반환값 — 재귀(Functions Recursion) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Function Parameters — https://www.w3schools.com/c/c_functions_parameters.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Function Parameters" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: c-functions-pointers
|
||||
title: "C Function Pointer"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["pointer to function", "function pointer array", "C 함수 포인터"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "function-pointers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_pointers.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Function Pointer]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A function's NAME already acts as a pointer to its own code, even before you declare any explicit function-pointer variable — `ptr = add;` and `ptr = &add;` are shown to be IDENTICAL, meaning `add` (bare, no parentheses) is already an address in the same sense `&myAge` was an address for a variable, and declaring `int (*ptr)(int, int)` just gives you a variable that can hold, reassign, and pass around that already-existing address. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Function pointer declaration** — `returnType (*pointerName)(paramType1, paramType2, ...);` (parentheses around `*pointerName` are required). [S1]
|
||||
- **Assignment equivalence** — `ptr = add;` and `ptr = &add;` do the same thing, since a function's name is already its address. [S1]
|
||||
- **Call equivalence** — `ptr(5, 3);` and `(*ptr)(5, 3);` both correctly call the pointed-to function. [S1]
|
||||
- **Choosing behavior at RUNTIME** — unlike a normal function call (fixed at compile time), a function pointer lets the program decide WHICH function to run while it's already executing. [S1]
|
||||
- **Function pointer array** — storing multiple function pointers in one array (`void (*operations[3])() = {add, subtract, multiply};`) enables selecting a function by INDEX, e.g. from user input, powering menus/calculators. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic function pointer declaration, assignment, and call: `int add(int a, int b) { return a + b; } int (*ptr)(int, int) = add; int result = ptr(5, 3); // same as add(5,3)`. [S1]
|
||||
- Passing a function pointer as an argument (a callback): `void greet(void (*func)()) { func(); } greet(greetMorning); greet(greetEvening);`. [S1]
|
||||
- A calculator selecting among functions by user-entered index: `void (*operations[3])(int, int) = { add, subtract, multiply }; scanf("%d", &choice); operations[choice](x, y);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **함수 이름은 이미 포인터**: ptr = add와 ptr = &add가 완전히 동일하게 작동한다는 점에서, 함수 이름 자체가 이미 메모리상 코드 시작 주소를 가리키는 포인터 역할을 하고 있음이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
사용자가 숫자를 입력해 덧셈/뺄셈/곱셈 중 하나를 선택하는 계산기 예제가 원문에서 직접 실전 활용 사례로 제시됨(함수 포인터 배열 + scanf 조합). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Selecting which function to run at runtime via a function pointer array indexed by user input (C):
|
||||
```c
|
||||
void add(int a, int b) { printf("Result: %d\n", a + b); }
|
||||
void subtract(int a, int b) { printf("Result: %d\n", a - b); }
|
||||
void multiply(int a, int b) { printf("Result: %d\n", a * b); }
|
||||
int main() {
|
||||
int choice, x = 10, y = 5;
|
||||
void (*operations[3])(int, int) = { add, subtract, multiply };
|
||||
scanf("%d", &choice);
|
||||
if (choice >= 0 && choice < 3) {
|
||||
operations[choice](x, y);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Recursion]], [[C Pointers]], [[C Functions Callback]]
|
||||
- **참조 맥락:** 함수 포인터 — 콜백 함수(Functions Callback) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Function Pointer — https://www.w3schools.com/c/c_functions_pointers.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Function Pointer" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-functions-recursion
|
||||
title: "C Recursion"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["recursive function", "base case", "factorial recursion", "C 재귀"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "functions", "recursion"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_functions_recursion.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Recursion]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Every recursive function in the source's examples relies on a single structural guarantee: the function ONLY calls itself when a shrinking condition still holds (`k > 0`, `n > 0`, `n > 1`) and returns a plain value OTHERWISE — the source's own warning that recursion "can be quite easy to slip into writing a function which never terminates" is really pointing at what happens if that shrinking condition is missing or wrong, not at recursion itself being inherently risky. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Recursion** — a function calling ITSELF, breaking a complex problem into smaller instances of the same problem. [S1]
|
||||
- **Base case** — the condition under which the function STOPS calling itself and returns directly (e.g. `k > 0` becoming false), essential for termination. [S1]
|
||||
- **Unwinding accumulation** — each recursive call's `return` combines its own contribution with the result of the smaller sub-call (`return k + sum(k - 1);`), building up the final answer as calls return in reverse order. [S1]
|
||||
- **Risk of non-termination or excess resource use** — without a solid base case, recursion can run forever or exhaust memory/processor time. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Summing 1 to 10 via recursion: `int sum(int k) { if (k > 0) { return k + sum(k - 1); } else { return 0; } }` — unfolds as `10 + (9 + (8 + ... + sum(0)))`. [S1]
|
||||
- Countdown via recursion: `void countdown(int n) { if (n > 0) { printf("%d ", n); countdown(n - 1); } }` — stops calling itself once `n` reaches 0. [S1]
|
||||
- Factorial via recursion: `int factorial(int n) { if (n > 1) { return n * factorial(n - 1); } else { return 1; } }` — factorial(5) = 5×4×3×2×1 = 120; by definition 0! is also 1. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **재귀의 종료 조건이 핵심 위험 요소**: 종료되지 않는 함수나 과도한 메모리/CPU를 쓰는 함수를 실수로 작성하기 쉽다는 경고가 있지만, 이는 결국 축소 조건(base case)이 없거나 잘못됐을 때 발생하는 문제임이 예제들에서 공통적으로 드러남. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
5의 팩토리얼(5×4×3×2×1=120)을 재귀로 계산하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A recursive function with a clear base case that guarantees termination (C):
|
||||
```c
|
||||
int factorial(int n) {
|
||||
if (n > 1) {
|
||||
return n * factorial(n - 1);
|
||||
} else {
|
||||
return 1; // base case
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Parameters]], [[C Memory Allocate]], [[C Functions Pointers]]
|
||||
- **참조 맥락:** 재귀 — 함수 포인터(Functions Pointers) 챕터로 이어짐, 스택 메모리(Memory Allocate 챕터의 스택 오버플로우 개념)와 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Recursion — https://www.w3schools.com/c/c_functions_recursion.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Recursion" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-get-started
|
||||
title: "C Get Started"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["installing C", "Code::Blocks", "gcc setup", "C 시작하기"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "setup", "ide"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_getstarted.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Get Started]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Unlike interpreted languages covered elsewhere in this wiki (Python, PHP, JavaScript), C requires a genuinely separate COMPILATION step before execution — the source explicitly frames the whole beginner workflow as "you wrote C code, the compiler turned it into a program, and the computer ran it," meaning even the simplest C setup inherently involves an editor AND a compiler as two distinct required tools, not one interpreter. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Two required tools** — a text editor to write code, and a COMPILER to translate C source into machine code the computer can run directly. [S1]
|
||||
- **IDE as a bundle** — an IDE (e.g. Code::Blocks, Eclipse, Visual Studio) packages both editor and compiler together, and typically adds error-finding help. [S1]
|
||||
- **`.c` file extension** — C source files must always end in `.c`. [S1]
|
||||
- **Web-based editors** — W3Schools' own online editor works without installation but the source notes such tools "often have limited features" compared to a full IDE. [S1]
|
||||
- **Multi-step build workflow** — write code → Build and Run → compiler translates → OS executes the resulting program, distinct from an interpreted run-immediately model. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Minimal Hello World used for setup verification: `#include <stdio.h> int main() { printf("Hello World!"); return 0; }`. [S1]
|
||||
- Recommended beginner IDE: Code::Blocks, downloaded via the `mingw-setup.exe` installer which bundles both editor and compiler (MinGW). [S1]
|
||||
- Expected successful output after Build & Run: `Hello World! Process returned 0 (0x0) execution time : 0.011 s Press any key to continue.`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **웹 기반 에디터의 한계**: 설치 없이 시작할 수 있는 온라인 에디터는 편리하지만 기능이 제한적이라는 점이 명시적으로 언급됨 — 실제 프로젝트에는 로컬 IDE 설치를 권장. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — Code::Blocks + MinGW 조합으로 편집기와 컴파일러를 한 번에 설치하는 것이 실전 초보자 환경 구축의 대표 방법이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The verification program used to confirm a working compiler setup (C):
|
||||
```c
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
printf("Hello World!");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Intro]], [[C Syntax]]
|
||||
- **참조 맥락:** 개발 환경 설정 — 문법(Syntax) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Get Started — https://www.w3schools.com/c/c_getstarted.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Get Started" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: c-input-validation
|
||||
title: "C Input Validation"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["validate number range", "sscanf validation", "C 입력 검증"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "input-validation", "scanf", "sscanf"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_input_validation.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Input Validation]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The integer-validation example doesn't use `scanf()` directly to detect bad input — it reads the RAW LINE with `fgets()` first, then tries to parse it with `sscanf()` and checks whether that parse SUCCEEDED (`== 1`), meaning robust validation in C separates "getting text from the user" from "trying to interpret that text as a number," rather than trusting `scanf()`'s own format-matching to gracefully reject non-numeric input. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Range validation via a do-while loop** — repeatedly prompt until the entered value falls within an allowed range; `while (getchar() != '\n');` clears any leftover characters in the input buffer after `scanf()`. [S1]
|
||||
- **Empty-text validation** — read with `fgets()`, strip the trailing newline (`name[strcspn(name, "\n")] = 0;`), then loop while the resulting string length is 0. [S1]
|
||||
- **Integer-format validation** — read the raw line as a STRING via `fgets()`, then attempt `sscanf(input, "%d", &number)`; if it returns `1` (one successful conversion), the input was a valid integer — otherwise, prompt again. [S1]
|
||||
- **Buffer-clearing necessity** — leftover characters (like an unconsumed newline) in the input stream after `scanf()` can silently corrupt the NEXT read unless explicitly cleared. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Range-bounded input with buffer clearing: `do { printf("Choose a number between 1 and 5: "); scanf("%d", &number); while (getchar() != '\n'); } while (number < 1 || number > 5);`. [S1]
|
||||
- Rejecting empty text input: `do { fgets(name, sizeof(name), stdin); name[strcspn(name, "\n")] = 0; } while (strlen(name) == 0);`. [S1]
|
||||
- Validating that input is actually an integer via sscanf's return value: `while (fgets(input, sizeof(input), stdin)) { if (sscanf(input, "%d", &number) == 1) { break; } else { printf("Invalid input. Try again: "); } }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **문자열로 먼저 읽고 sscanf로 파싱을 검증하는 전략**: scanf()로 직접 숫자를 받는 대신 fgets()로 원문을 통째로 받은 뒤 sscanf()의 반환값(성공한 변환 개수)을 확인하는 방식이 잘못된 입력을 더 안전하게 걸러낸다는 점이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
1~5 범위의 숫자 선택, 빈 이름 거부, 문자가 아닌 정수만 허용하는 세 가지 검증 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Validating that user input is actually an integer using fgets() + sscanf()'s return value (C):
|
||||
```c
|
||||
int number;
|
||||
char input[100];
|
||||
printf("Enter a number: ");
|
||||
while (fgets(input, sizeof(input), stdin)) {
|
||||
if (sscanf(input, "%d", &number) == 1) {
|
||||
break; // valid integer
|
||||
} else {
|
||||
printf("Invalid input. Try again: ");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Error Handling]], [[C User Input]], [[C Debugging]]
|
||||
- **참조 맥락:** 입력 검증 — 디버깅(Debugging) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Input Validation — https://www.w3schools.com/c/c_input_validation.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Input Validation" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-intro
|
||||
title: "C Introduction"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["what is c", "C vs C++", "C 소개"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "intro"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_intro.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Intro]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source frames C's core value proposition as a LEARNING INVESTMENT, not just a language choice — "if you know C, you will have no problem learning other popular programming languages such as Java, Python, C++, C#" — positioning C's tight syntax and manual memory model as the shared ancestor whose concepts transfer forward into most mainstream languages. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Origin** — created by Dennis Ritchie at Bell Labs in 1972; closely tied to UNIX since much of UNIX itself was written in C. [S1]
|
||||
- **Primary domains** — operating systems, embedded devices, performance-critical software (databases, system tools), game engines/graphics, and core libraries underlying other languages. [S1]
|
||||
- **Multiple language standards** — C90, C99, C11, C17, and newer; the tutorial focuses on modern widely-supported C and flags standard-specific differences when relevant. [S1]
|
||||
- **C vs C++** — C++ is an extension of C; C is primarily procedural (function-based), while C++ adds classes/objects for object-oriented programming — but C can still organize data via structs and scale to large programs without C++'s added features. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Minimal working example: `#include <stdio.h> int main() { char name[] = "John"; printf("Hello %s", name); return 0; }` producing `Hello John`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **C도 대규모 프로그램이 가능하다는 점**: C++이 클래스라는 추가 기능을 얹은 것뿐이며, C만으로도 구조체를 이용해 데이터를 조직하고 큰 프로그램을 만들 수 있다는 점이 명시적으로 강조됨(C가 단순히 "작은 프로그램용"이라는 오해를 교정). [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — Windows/Linux/macOS의 일부, 자동차·TV 등 임베디드 기기, 게임 엔진 등이 원문에서 언급된 C의 대표적 실전 활용 분야다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Minimal C program printing a formatted greeting:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
char name[] = "John";
|
||||
printf("Hello %s", name);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Get Started]], [[C Syntax]]
|
||||
- **참조 맥락:** C 튜토리얼 첫 챕터 — 개발 환경 설정(Get Started) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Introduction — https://www.w3schools.com/c/c_intro.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Introduction" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-macros
|
||||
title: "C Preprocessor and Macros"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["#define", "#ifdef", "conditional compilation", "C 전처리기와 매크로"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "preprocessor", "macros"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_macros.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Preprocessor and Macros]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`#define PI 3.14` doesn't create a variable at all — the preprocessor performs a pure TEXT REPLACEMENT of every literal occurrence of `PI` with `3.14` BEFORE the compiler ever sees the code, meaning macros exist in an entirely different phase from variables/constants (which are compiled), which is also why parameterized macros like `SQUARE(x)` need careful parenthesization — they're substituting raw text, not evaluating an expression with real function-call semantics. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Preprocessor** — runs BEFORE actual compilation; handles directives (lines starting with `#`) like including files and defining macros. [S1]
|
||||
- **`#include`** — angle brackets `< >` for standard libraries, double quotes `" "` for your own header files. [S1]
|
||||
- **`#define NAME value`** — creates a macro; every literal occurrence of `NAME` in the code is textually replaced with `value` before compilation. [S1]
|
||||
- **Parameterized macros** — `#define SQUARE(x) ((x) * (x))` behaves like a function shortcut, but is really TEXT SUBSTITUTION, so careful parenthesization is required to avoid operator-precedence mistakes. [S1]
|
||||
- **`#ifdef` / `#ifndef`** — conditional compilation; includes or skips code blocks depending on whether a macro is defined, useful for debug builds or program variants. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic value macro: `#define PI 3.14 int main() { printf("Value of PI: %.2f\n", PI); return 0; }`. [S1]
|
||||
- Parameterized macro: `#define SQUARE(x) ((x) * (x)) printf("Square of 4: %d\n", SQUARE(4));`. [S1]
|
||||
- Conditional compilation gated on a defined macro: `#define DEBUG int main() { #ifdef DEBUG printf("Debug mode is ON\n"); #endif return 0; }` — if `DEBUG` were undefined, that block would be skipped entirely. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **매크로는 변수가 아니라 텍스트 치환**: #define PI 3.14는 컴파일 전에 코드상의 PI를 문자 그대로 3.14로 바꿔치기하는 전처리 단계 작업이며, 변수나 상수처럼 컴파일되는 개념이 아니라는 점이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
DEBUG 매크로가 정의되어 있을 때만 디버그 메시지를 출력하는 조건부 컴파일이 원문에서 직접 실전 활용 사례로 제시됨(디버깅이나 프로그램 버전 분기에 유용). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Conditional compilation — code included only if a macro is defined (C):
|
||||
```c
|
||||
#define DEBUG
|
||||
int main() {
|
||||
#ifdef DEBUG
|
||||
printf("Debug mode is ON\n");
|
||||
#endif
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Type Conversion]], [[C Organize Code]], [[C Null]]
|
||||
- **참조 맥락:** 전처리기와 매크로 — NULL(Null) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Preprocessor and Macros — https://www.w3schools.com/c/c_macros.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Preprocessor and Macros" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-math
|
||||
title: "C Math Functions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["math.h", "sqrt ceil floor pow", "C 수학 함수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "math", "math.h"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_math.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Math Functions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`ceil()` and `floor()` both return a `float`/`double`, NOT an `int` — printing `ceil(1.4)` with `%f` still shows a decimal-formatted result (`2.000000`), meaning "rounding" in C's math library doesn't convert the value to an integer type; it just replaces the fractional part while preserving the floating-point representation, so further formatting or casting is still the caller's job. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`<math.h>`** — required header for math functions beyond basic arithmetic operators. [S1]
|
||||
- **`sqrt(x)`** — returns the square root of `x`. [S1]
|
||||
- **`ceil(x)`** — rounds UP to the nearest integer value (still returned as a float/double). [S1]
|
||||
- **`floor(x)`** — rounds DOWN to the nearest integer value (still returned as a float/double). [S1]
|
||||
- **`pow(x, y)`** — returns x raised to the power of y (xʸ). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Square root: `printf("%f", sqrt(16));`. [S1]
|
||||
- Rounding up vs down on the same value: `printf("%f", ceil(1.4)); printf("%f", floor(1.4));` — ceil gives 2.000000, floor gives 1.000000. [S1]
|
||||
- Exponentiation: `printf("%f", pow(4, 3));` — 4³ = 64. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — sqrt/ceil/floor/pow는 게임 로직이나 그래픽 계산 등에서 흔히 결합해 쓰이는 기본 수학 함수 집합이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Rounding up and down, both still returned as floating-point values (C):
|
||||
```c
|
||||
#include <math.h>
|
||||
printf("%f", ceil(1.4)); // 2.000000
|
||||
printf("%f", floor(1.4)); // 1.000000
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Strings Functions]], [[C Random Numbers]]
|
||||
- **참조 맥락:** 수학 함수 — 난수 생성(Random Numbers) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Math Functions — https://www.w3schools.com/c/c_math.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Math Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-memory-access
|
||||
title: "C Access Memory"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["dynamic memory access", "reinterpreting bytes", "C 동적 메모리 접근"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory", "dynamic-memory"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_access.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Access Memory]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Dynamically allocated memory has NO type of its own at all — it's "just a sequence of bytes," and the SAME 4 bytes can be read as one `int` OR as four separate `char` values depending purely on which pointer TYPE you use to view them, proven by the example where `ptr1[0] = 1684234849` (an int) and `ptr2[0..3]` (a char reinterpretation of the identical bytes) both successfully read the same memory as completely different things. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Dynamic memory behaves like an array** — indexable via `ptr[i]` or dereferenceable via `*ptr` for the first element, just like a regular array. [S1]
|
||||
- **No inherent data type** — allocated memory is raw bytes; its "type" is entirely a matter of interpretation, determined by whatever pointer type is used to access it. [S1]
|
||||
- **Type reinterpretation via pointer casting** — casting an `int*` to a `char*` (`(char*) ptr1`) lets the SAME underlying bytes be read as individual characters instead of one integer. [S1]
|
||||
- **Index vs. dereference for the first element** — `ptr[0] = 12;` and `*ptr = 12;` are equivalent ways to write to the first allocated element. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Allocating and accessing dynamic memory both ways: `int *ptr; ptr = calloc(4, sizeof(*ptr)); *ptr = 2; ptr[1] = 4; ptr[2] = 6;`. [S1]
|
||||
- Reinterpreting the same 4 bytes as an int vs. four chars: `int *ptr1 = malloc(4); char *ptr2 = (char*) ptr1; ptr1[0] = 1684234849; printf("%d is %c %c %c %c", *ptr1, ptr2[0], ptr2[1], ptr2[2], ptr2[3]);` — the same 4 bytes printed once as a number and once as four ASCII characters. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **할당된 메모리는 타입이 없는 바이트 시퀀스**: 동일한 4바이트 메모리가 포인터 타입에 따라 하나의 int로도, 4개의 char로도 해석될 수 있다는 점이 직접 예시로 증명됨 — 타입은 데이터 자체가 아니라 접근 방식이 결정한다. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 동일한 메모리를 int 포인터와 char 포인터로 각각 해석하는 기법이 저수준 바이트 조작이나 타입 캐스팅이 필요한 실전 상황에서 활용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The same 4 bytes of allocated memory reinterpreted as an int vs. four chars via pointer casting (C):
|
||||
```c
|
||||
int *ptr1 = malloc(4);
|
||||
char *ptr2 = (char*) ptr1;
|
||||
ptr1[0] = 1684234849;
|
||||
printf("%d is %c %c %c %c", *ptr1, ptr2[0], ptr2[1], ptr2[2], ptr2[3]);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Pointer To Pointer]], [[C Memory Management]], [[C Memory Allocate]]
|
||||
- **참조 맥락:** 동적 메모리 접근 — 메모리 관리(Memory Management) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Access Memory — https://www.w3schools.com/c/c_memory_access.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Access Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: c-memory-address
|
||||
title: "C Memory Address"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["reference operator", "%p specifier", "C 메모리 주소"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory", "pointers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_address.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Memory Address]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`&myAge` isn't just a debugging curiosity for printing hex addresses — the source explicitly identifies it as a "pointer" in its own right, meaning the concept of "getting a memory address" and "creating a pointer value" are the SAME operation viewed from two angles, setting up the entire next chapter's pointer syntax as a direct extension of this one operator (`&`). [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Memory address** — the physical location where a variable's value is actually stored on the computer. [S1]
|
||||
- **`&` (reference/address-of operator)** — retrieves a variable's memory address. [S1]
|
||||
- **`%p` format specifier** — the correct printf specifier for printing a memory address/pointer value (not `%d`). [S1]
|
||||
- **Hexadecimal representation** — memory addresses print in `0x...` form; the exact value varies by machine/run and isn't meant to be predicted. [S1]
|
||||
- **Why pointers matter** — they let a program manipulate memory directly, reducing code size and improving performance — described as one of the things that distinguishes C from languages like Python and Java. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Getting and printing a variable's address: `int myAge = 43; printf("%p", &myAge); // Outputs 0x7ffe5367e044`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 챕터의 & 연산자 개념이 다음 챕터(Pointers)에서 실제 포인터 변수 선언의 기초로 그대로 이어진다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Getting a variable's memory address with the reference operator (C):
|
||||
```c
|
||||
int myAge = 43;
|
||||
printf("%p", &myAge); // Outputs 0x7ffe5367e044
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Typedef]], [[C Pointers]]
|
||||
- **참조 맥락:** 포인터/메모리 섹션 첫 챕터 — 포인터(Pointers) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Memory Address — https://www.w3schools.com/c/c_memory_address.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Memory Address" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-memory-allocate
|
||||
title: "C Allocate Memory"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["malloc calloc", "static vs dynamic memory", "stack memory", "C 메모리 할당"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management", "malloc", "calloc"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_allocate.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Allocate Memory]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`sizeof(*ptr1)` and `sizeof(ptr1)` look nearly identical but measure two completely different things — the FIRST measures the size of the data the pointer points to (correct for allocation), while the SECOND measures the size of the pointer variable itself (usually 8 bytes, the address size) — and the source explicitly flags forgetting the `*` as a real, easy-to-make mistake that silently allocates the wrong amount of memory. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Static memory** — reserved automatically at COMPILE time for regular variables; fixed size, cannot be resized after creation (e.g. an array declared for 20 elements always occupies that space, even if only 12 are used). [S1]
|
||||
- **Dynamic memory** — reserved at RUNTIME, giving full programmer control over how much memory is used; only accessible via pointers, never owned by a plain variable. [S1]
|
||||
- **`malloc(size)`** — allocates `size` bytes; the content is UNPREDICTABLE/uninitialized until written. [S1]
|
||||
- **`calloc(amount, size)`** — allocates `amount` items of `size` bytes each, AND zero-initializes all of it; slightly less efficient than `malloc()` because of the zeroing step. [S1]
|
||||
- **`sizeof(*ptr)` vs `sizeof(ptr)`** — the former measures the pointed-to data's size (correct for sizing an allocation); the latter measures the pointer variable's own size (usually 8 bytes on 64-bit systems), a common mistake. [S1]
|
||||
- **`sizeof` can't measure total allocated memory** — it only reports the size of ONE element's type, so total dynamic allocation size must be computed manually (`count * sizeof(type)`). [S1]
|
||||
- **Stack memory** — a form of dynamic memory automatically reserved for variables declared INSIDE functions; freed automatically when the function returns; excessive recursion can exhaust it, causing a "stack overflow." [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Static memory waste example: `int students[20]; // reserves 80 bytes even if only 12 students actually attend`. [S1]
|
||||
- Correctly sizing a dynamic allocation with `sizeof(*ptr)`: `int *ptr1, *ptr2; ptr1 = malloc(sizeof(*ptr1)); ptr2 = calloc(1, sizeof(*ptr2));`. [S1]
|
||||
- Computing total dynamic memory manually (sizeof alone can't do it): `int *students; int numStudents = 12; students = calloc(numStudents, sizeof(*students)); printf("%d", numStudents * sizeof(*students)); // 48 bytes`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **sizeof(*ptr) vs sizeof(ptr)의 차이**: 별표를 빠뜨리면 포인터가 가리키는 데이터의 크기가 아니라 포인터 자체의 크기(보통 8바이트)를 측정하게 된다는 점이 실수하기 쉬운 부분으로 명시적으로 경고됨. [S1]
|
||||
- **정적 메모리의 낭비 가능성**: 20명분 배열을 만들었는데 실제 12명만 참여하면 8명분 공간이 낭비되지만, 프로그램은 정상 작동하며 손상되지 않는다는 점이 확인됨(단지 비효율적일 뿐). [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
학생 수(numStudents)만큼만 calloc으로 메모리를 할당해 정적 배열의 낭비 문제를 해결하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Correctly sizing an allocation using sizeof(*ptr), not sizeof(ptr) (C):
|
||||
```c
|
||||
int *ptr1, *ptr2;
|
||||
ptr1 = malloc(sizeof(*ptr1)); // correct: size of the pointed-to int
|
||||
ptr2 = calloc(1, sizeof(*ptr2)); // correct: size of the pointed-to int
|
||||
// sizeof(ptr1) would instead measure the pointer itself (usually 8 bytes)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Management]], [[C Data Types Sizeof]], [[C Memory Deallocate]]
|
||||
- **참조 맥락:** 메모리 할당 — 메모리 해제(Memory Deallocate) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Allocate Memory — https://www.w3schools.com/c/c_memory_allocate.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Allocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: c-memory-deallocate
|
||||
title: "C Deallocate Memory"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["free() function", "memory leak", "set pointer to NULL", "C 메모리 해제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management", "free", "memory-leak"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_deallocate.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Deallocate Memory]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A memory leak isn't caused by forgetting `free()` in the obvious sense — the source's three worked examples show it happens when the POINTER itself is lost (overwritten to point elsewhere, scoped inside a function that ends, or clobbered by a failed `realloc()` returning NULL) while the memory it referenced is STILL allocated but now permanently unreachable — meaning the memory isn't the problem, losing the only handle to it is. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`free(pointer)`** — releases previously allocated dynamic memory back for reuse by other parts of the program or other programs. [S1]
|
||||
- **Set to NULL after freeing** — best practice; prevents accidentally continuing to use a freed (now invalid) pointer. [S1]
|
||||
- **Memory leak** — dynamically allocated memory that is never freed, typically because the ONLY pointer referencing it was lost, not because `free()` was simply forgotten in an obvious spot. [S1]
|
||||
- **Leak pattern 1: pointer overwritten** — reassigning a pointer variable to a new address (e.g. `&x`) severs its only link to the previously `calloc()`'d memory. [S1]
|
||||
- **Leak pattern 2: pointer scoped to a function** — a local pointer variable disappears when its function returns, but the memory it pointed to remains allocated and now unreachable. [S1]
|
||||
- **Leak pattern 3: failed `realloc()` overwrites the original pointer** — if `realloc()` fails and returns `NULL`, assigning that `NULL` directly back to the SAME variable destroys the only reference to the still-valid original memory. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic free with error checking and NULL-setting: `int *ptr; ptr = malloc(sizeof(*ptr)); if (ptr == NULL) { printf("Unable to allocate memory"); return 1; } *ptr = 20; free(ptr); ptr = NULL;`. [S1]
|
||||
- Leak via pointer reassignment: `int x = 5; int *ptr; ptr = calloc(2, sizeof(*ptr)); ptr = &x;` — the calloc'd memory is now unreachable. [S1]
|
||||
- Leak via function-scoped pointer: `void myFunction() { int *ptr; ptr = malloc(sizeof(*ptr)); }` — memory allocated inside persists after the function returns but can never be freed or accessed again. [S1]
|
||||
- Leak via unchecked realloc failure: `ptr = realloc(ptr, 2*sizeof(*ptr));` — if this fails, `ptr` becomes NULL and the original memory address is lost forever (the correct fix, shown in the Reallocate chapter, is to use a TEMPORARY pointer for the realloc result). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **메모리 누수의 진짜 원인은 포인터 분실**: free()를 안 써서가 아니라, 메모리를 가리키던 유일한 포인터가 덮어써지거나(재대입/함수 종료/realloc 실패) 사라져서 더 이상 접근할 수 없게 되는 것이 메모리 누수의 실제 메커니즘이라는 점이 세 가지 예제로 구체적으로 증명됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — free() 후 포인터를 NULL로 설정하는 습관이 실수로 해제된 메모리를 재사용하는 버그를 방지하는 실전 관행으로 강조된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Freeing memory and setting the pointer to NULL to prevent accidental reuse (C):
|
||||
```c
|
||||
int *ptr;
|
||||
ptr = malloc(sizeof(*ptr));
|
||||
if (ptr == NULL) {
|
||||
printf("Unable to allocate memory");
|
||||
return 1;
|
||||
}
|
||||
*ptr = 20;
|
||||
free(ptr);
|
||||
ptr = NULL; // prevents accidental use-after-free
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Allocate]], [[C Memory Reallocate]], [[C Null]]
|
||||
- **참조 맥락:** 메모리 해제 — 메모리 재할당(Memory Reallocate) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Deallocate Memory — https://www.w3schools.com/c/c_memory_deallocate.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Deallocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-memory-management
|
||||
title: "C Memory Management"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["memory management overview", "C 메모리 관리"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_management.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Memory Management]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Manual memory management is presented as a genuine TRADE, not a burden imposed for no reason — the source frames it explicitly as "complicated... but also quite powerful when used correctly," meaning C hands the programmer full responsibility for allocation/deallocation specifically because that same responsibility is what enables performance optimization impossible in languages with automatic garbage collection. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Memory management** — the process of controlling how much memory a program uses, via three operations: allocation, reallocation, and deallocation ("freeing"). [S1]
|
||||
- **Automatic sizing for basic variables** — C automatically reserves the correct byte size for `int`/`float`/`double`/`char` variables; `sizeof` reveals these sizes (4/4/8/1 bytes respectively). [S1]
|
||||
- **Manual responsibility** — unlike some languages, C requires the PROGRAMMER to manage memory explicitly, which is more error-prone but enables finer performance control. [S1]
|
||||
- **Pointers as the memory-management tool** — since dynamic memory is only reachable via pointers, memory management is inherently pointer-based work. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Confirming basic type sizes via sizeof: `int myInt; float myFloat; double myDouble; char myChar; printf("%zu\n", sizeof(myInt)); // 4 printf("%zu\n", sizeof(myDouble)); // 8`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **수동 메모리 관리는 강력함과 위험의 트레이드오프**: 복잡하지만 제대로 사용하면 매우 강력하다는 점, 그리고 포인터를 다룰 때는 다른 메모리 주소의 데이터를 손상시킬 위험이 있으니 주의해야 한다는 점이 함께 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 챕터가 개관하는 할당/재할당/해제 세 가지 개념이 다음 챕터들(Memory Allocate/Reallocate/Deallocate)에서 각각 상세히 다뤄지는 로드맵 역할을 한다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Checking the actual byte sizes of C's basic types with sizeof (C):
|
||||
```c
|
||||
int myInt;
|
||||
float myFloat;
|
||||
double myDouble;
|
||||
char myChar;
|
||||
printf("%zu\n", sizeof(myInt)); // 4 bytes
|
||||
printf("%zu\n", sizeof(myFloat)); // 4 bytes
|
||||
printf("%zu\n", sizeof(myDouble)); // 8 bytes
|
||||
printf("%zu\n", sizeof(myChar)); // 1 byte
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Access]], [[C Memory Allocate]]
|
||||
- **참조 맥락:** 메모리 관리 개관 — 메모리 할당(Memory Allocate) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Memory Management — https://www.w3schools.com/c/c_memory_management.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Memory Management" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
id: c-memory-reallife
|
||||
title: "C Memory Management Example"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["dynamic array list", "growable list implementation", "C 메모리 관리 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management", "dynamic-array"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Memory Management Example]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The chapter directly answers WHY growable lists grow by a chunk of 10 rather than 1-at-a-time: reallocating memory too FREQUENTLY is inefficient even though it wastes less space, so the design deliberately trades a small amount of unused memory for far fewer (and cheaper) reallocation calls — an explicit memory-vs-performance balancing act rather than an arbitrary constant. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Growable list via struct + dynamic memory** — a `struct list { int *data; int numItems; int size; }` tracks the actual data pointer, how many items are currently used, and how much capacity is currently allocated. [S1]
|
||||
- **Batch-growth strategy** — when the list fills up, capacity grows by a FIXED CHUNK (+10 items) rather than exactly by 1, trading some unused memory for fewer, cheaper reallocation calls. [S1]
|
||||
- **Safe realloc pattern reused** — `addToList()` uses a temporary pointer (`tmp`) for the `realloc()` result, only committing `myList->data`/`myList->size` AFTER confirming `tmp` isn't NULL. [S1]
|
||||
- **Struct passed by pointer to a function** — `addToList(struct list *myList, int item)` receives the list by pointer (using `->`) so it can permanently mutate the caller's actual list state, not a copy. [S1]
|
||||
- **Fixed-size arrays can't do this** — the chapter opens by contrasting this against regular C arrays, whose length is fixed at creation and can never grow. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- The list struct and its three roles: `struct list { int *data; int numItems; int size; };` — `data` points to the dynamic storage, `numItems` tracks current fill level, `size` tracks total current capacity. [S1]
|
||||
- The growth-trigger check inside `addToList()`: `if (myList->numItems == myList->size) { int newSize = myList->size + 10; int *tmp = realloc(myList->data, newSize * sizeof(int)); if (tmp == NULL) { printf("Memory resize failed\n"); return; } myList->data = tmp; myList->size = newSize; }`. [S1]
|
||||
- Appending after ensuring capacity: `myList->data[myList->numItems] = item; myList->numItems++;`. [S1]
|
||||
- Explicit rationale for the +10 chunk size: "Optimizing is a balancing act between memory and performance... reallocating memory too frequently can be inefficient." [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **+10씩 늘리는 이유는 메모리와 성능의 균형**: 정확히 필요한 만큼만 늘리지 않고 10개씩 뭉텅이로 늘리는 이유가 재할당을 너무 자주 하면 비효율적이기 때문이라는 점이 명시적으로 설명됨 — 정확한 개수(예: 44개)를 미리 안다면 한 번에 그만큼만 할당하는 것이 더 낫다고도 언급됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
44개의 항목을 하나씩 추가하면서 필요할 때마다 자동으로 용량을 10개씩 늘려가는 리스트 구현이 원문에서 직접 실전 활용 사례로 제시되며, 배열/구조체/포인터/동적 메모리 챕터 전체를 종합한 완결편 역할을 한다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Growing a dynamic list by a fixed chunk size using the safe temporary-pointer realloc pattern (C):
|
||||
```c
|
||||
void addToList(struct list *myList, int item) {
|
||||
if (myList->numItems == myList->size) {
|
||||
int newSize = myList->size + 10;
|
||||
int *tmp = realloc(myList->data, newSize * sizeof(int));
|
||||
if (tmp == NULL) {
|
||||
printf("Memory resize failed\n");
|
||||
return;
|
||||
}
|
||||
myList->data = tmp;
|
||||
myList->size = newSize;
|
||||
}
|
||||
myList->data[myList->numItems] = item;
|
||||
myList->numItems++;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Struct]], [[C Functions]], [[C Structs Pointers]]
|
||||
- **참조 맥락:** 포인터 및 메모리 섹션 마지막 — 함수(Functions) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Memory Management Example — https://www.w3schools.com/c/c_memory_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Memory Management Example" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
id: c-memory-reallocate
|
||||
title: "C Reallocate Memory"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["realloc() function", "temporary pointer pattern", "C 메모리 재할당"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management", "realloc"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_reallocate.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Reallocate Memory]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`realloc()` may or may not move the data to a NEW address — it tries to resize in place first, but if it can't, it silently allocates elsewhere and returns the new address, which means the ORIGINAL address becomes immediately unsafe to use the moment reallocation succeeds at a different location, making it essential to always capture `realloc()`'s return value into a SEPARATE temporary pointer rather than overwriting the original variable directly (since a failed call returns NULL and would otherwise destroy the only reference to the still-valid original memory). [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`realloc(ptr, newSize)`** — resizes previously allocated memory while PRESERVING its existing contents; returns either the SAME address (if resized in place) or a NEW address (if it had to move the data). [S1]
|
||||
- **Old address becomes invalid on move** — once `realloc()` returns a different address, the original address is no longer safe to use. [S1]
|
||||
- **NULL on failure** — if reallocation fails, `realloc()` returns `NULL`, and (per the previous chapter) the ORIGINAL memory remains valid and allocated. [S1]
|
||||
- **Temporary-pointer safety pattern** — assign `realloc()`'s result to a SEPARATE variable first, check it for `NULL`, and only then update the original pointer — directly overwriting the original pointer risks losing it if the call fails. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Growing an allocation from 4 to 6 integers: `size = 4 * sizeof(*ptr1); ptr1 = malloc(size); size = 6 * sizeof(*ptr1); ptr2 = realloc(ptr1, size);`. [S1]
|
||||
- Safe NULL-check pattern before committing the resized pointer: `ptr1 = malloc(4); ptr2 = realloc(ptr1, 8); if (ptr2 == NULL) { printf("Failed. Unable to resize memory"); } else { printf("Success..."); ptr1 = ptr2; }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **realloc 결과를 임시 포인터에 먼저 받아야 하는 이유**: realloc()이 실패하면 NULL을 반환하는데, 이를 원래 포인터 변수에 바로 대입해버리면 여전히 유효한 원본 메모리 주소를 잃어버리게 된다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 4개 정수에서 6개 정수로 메모리를 확장하는 예제가 실전에서 배열 크기를 동적으로 늘려야 할 때의 대표 패턴이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Safely resizing memory using a temporary pointer to avoid losing the original on failure (C):
|
||||
```c
|
||||
int *ptr1, *ptr2;
|
||||
ptr1 = malloc(4);
|
||||
ptr2 = realloc(ptr1, 8);
|
||||
if (ptr2 == NULL) {
|
||||
printf("Failed. Unable to resize memory");
|
||||
} else {
|
||||
ptr1 = ptr2; // safe to commit only after success
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Deallocate]], [[C Memory Struct]], [[C Memory RealLife]]
|
||||
- **참조 맥락:** 메모리 재할당 — 구조체와 동적 메모리(Memory Struct) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Reallocate Memory — https://www.w3schools.com/c/c_memory_reallocate.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Reallocate Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: c-memory-struct
|
||||
title: "C Structures and Dynamic Memory"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["malloc struct", "array of structs", "realloc struct array", "C 구조체 동적 메모리"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "memory-management", "structs"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_memory_struct.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Structures and Dynamic Memory]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Growing a dynamically-allocated array of structs with `realloc()` only extends the ALLOCATION — the newly added slots are explicitly UNINITIALIZED, meaning code that grows a 2-car array to 3 cars must manually `strcpy()`/assign values into the new index (`cars[2]`) before using it, or risk reading garbage; `realloc()` never zero-fills or default-constructs the extra space it creates. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`malloc(sizeof(struct Type))`** — allocates memory for exactly ONE struct instance, accessed via a pointer and the `->` arrow operator. [S1]
|
||||
- **`malloc(N * sizeof(struct Type))`** — allocates memory for an ARRAY of N structs at once, accessible via normal bracket indexing (`cars[0].brand`). [S1]
|
||||
- **`strcpy()` still required for string members** — even in dynamically allocated structs, `char[]` fields can't be assigned via `=` and still need `strcpy()`. [S1]
|
||||
- **Growing with `realloc()` + temporary pointer** — resizing a struct array follows the same safe pattern as the previous chapter (store the result in a temp pointer, check for NULL, only commit on success). [S1]
|
||||
- **New space from `realloc()` is uninitialized** — expanding from 2 to 3 struct elements leaves the new element's fields with undefined content until explicitly assigned. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Allocating memory for one struct: `struct Car *ptr = (struct Car*) malloc(sizeof(struct Car)); if (ptr == NULL) { ... } strcpy(ptr->brand, "Honda"); ptr->year = 2022; free(ptr);`. [S1]
|
||||
- Allocating an array of 3 structs at once: `struct Car *cars = (struct Car*) malloc(3 * sizeof(struct Car)); strcpy(cars[0].brand, "Ford"); cars[0].year = 2015;`. [S1]
|
||||
- Safely growing the array from 2 to 3 elements, then initializing the new slot: `struct Car *tmp = (struct Car*) realloc(cars, newCount * sizeof(struct Car)); if (tmp == NULL) { free(cars); ... } cars = tmp; strcpy(cars[2].brand, "Kia"); cars[2].year = 2022;` — the new element MUST be manually initialized since realloc leaves it undefined. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **realloc으로 늘어난 공간은 초기화되지 않음**: 배열을 2개에서 3개로 늘려도 새로 생긴 3번째 요소의 필드는 값이 정의되지 않은 상태이므로, 사용 전에 반드시 직접 초기화(strcpy/대입)해야 한다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
자동차 대수가 고정되지 않은 중고차 딜러십 프로그램에서 필요한 만큼만 구조체 메모리를 동적으로 할당하는 것이 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Growing a struct array and initializing the newly added, uninitialized slot (C):
|
||||
```c
|
||||
struct Car *tmp = (struct Car*) realloc(cars, newCount * sizeof(struct Car));
|
||||
if (tmp == NULL) {
|
||||
free(cars);
|
||||
printf("Reallocation failed.\n");
|
||||
return 1;
|
||||
}
|
||||
cars = tmp;
|
||||
// Must manually initialize the new element — realloc leaves it undefined
|
||||
strcpy(cars[2].brand, "Kia");
|
||||
cars[2].year = 2022;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Reallocate]], [[C Structs Pointers]], [[C Memory RealLife]]
|
||||
- **참조 맥락:** 구조체 동적 메모리 — 메모리 관리 실전 예제(Memory RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Structures and Dynamic Memory — https://www.w3schools.com/c/c_memory_struct.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Structures and Dynamic Memory" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-newline
|
||||
title: "C New Lines"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["\\n escape sequence", "blank line", "C 줄바꿈"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "newline", "escape-sequences"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_newline.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C New Lines]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`\n` isn't a "print a new line" command — it's an ESCAPE SEQUENCE representing a special character (moving the cursor to the start of the next line), placing it in the same category as `\t`, `\\`, and `\"` from earlier chapters, meaning "printing on multiple lines" in C is really just "printing one string that happens to contain a cursor-movement character," which is why doubling it up (`\n\n`) produces a blank line — the SAME character, repeated, moves the cursor down twice. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`\n`** — an escape sequence that moves the cursor to the beginning of the next line. [S1]
|
||||
- **Escape sequence** — a backslash-prefixed representation of a special character that can't be typed directly (this chapter's specific instance of the general pattern from the earlier Special Characters chapter). [S1]
|
||||
- **Multiple `\n` in a row = blank line(s)** — since each `\n` moves the cursor down one line, two in a row (`\n\n`) skips an entire visual line. [S1]
|
||||
- **Single printf(), multiple lines** — one `printf()` call CAN contain several `\n` characters to produce multi-line output, though the source notes this can hurt readability if overused. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Newline between two separate printf calls: `printf("Hello World!\n"); printf("I am learning C.");`. [S1]
|
||||
- Multiple lines from one printf call: `printf("Hello World!\nI am learning C.\nAnd it is awesome!");`. [S1]
|
||||
- Producing a blank line with doubled `\n`: `printf("Hello World!\n\n"); printf("I am learning C.");`. [S1]
|
||||
- Other common escape sequences reiterated: `\t` (horizontal tab), `\\` (literal backslash), `\"` (literal double quote). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **\n\n이 빈 줄을 만드는 이유**: \n 하나가 커서를 다음 줄로 한 번 이동시키므로, 두 번 연속 쓰면 한 줄을 건너뛰어 빈 줄처럼 보이게 된다는 점이 확인됨 — 특별한 "빈 줄" 문법이 있는 것이 아니라 동일한 이스케이프 문자의 반복일 뿐. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 여러 문장을 하나의 printf() 호출에 \n으로 이어붙이는 것이 코드를 짧게 만들지만 가독성을 해칠 수 있다는 점이 트레이드오프로 언급됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Producing a blank line by repeating the newline escape sequence (C):
|
||||
```c
|
||||
printf("Hello World!\n\n");
|
||||
printf("I am learning C.");
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Null]], [[C Strings Esc]], [[C Output]]
|
||||
- **참조 맥락:** C 튜토리얼 전체의 마지막 챕터 — 출력(Output)과 특수문자(Strings Esc) 챕터의 개념을 마무리로 재확인.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C New Lines — https://www.w3schools.com/c/c_newline.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C New Lines" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-null
|
||||
title: "C NULL"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["null pointer", "malloc NULL check", "C NULL"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "null", "pointers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_null.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C NULL]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`NULL` is the single unifying failure signal shared by two completely unrelated operations — `fopen()` (file access) and `malloc()` (memory allocation) — meaning the SAME defensive pattern (`if (ptr == NULL) { ...handle error... }`) applies whether the resource that might not exist is a file on disk or a block of RAM, because both operations return an ordinary pointer that's simply set to NULL on failure rather than raising any special error mechanism. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`NULL`** — represents a "null pointer": a pointer that points to nothing/nowhere. [S1]
|
||||
- **Failure signal, not an exception** — many C functions (`fopen()`, `malloc()`) return `NULL` when they fail, rather than throwing any error (since C has no exceptions). [S1]
|
||||
- **Universal safety check** — comparing any pointer to `NULL` before using it prevents crashes from accessing invalid memory. [S1]
|
||||
- **Same pattern across different resources** — the identical `if (ptr == NULL)` check applies whether guarding against a missing file OR a failed memory allocation. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- File-open failure check: `FILE *fptr = fopen("nothing.txt", "r"); if (fptr == NULL) { printf("Could not open file.\n"); return 1; }`. [S1]
|
||||
- Memory-allocation failure check (deliberately requesting an absurd amount): `int *numbers = (int*) malloc(100000000000000 * sizeof(int)); if (numbers == NULL) { printf("Memory allocation failed.\n"); return 1; }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **NULL 체크는 사용 전 필수 습관**: 크래시를 피하려면 포인터를 사용하기 전 항상 NULL인지 확인해야 한다는 점이 팁으로 강조되며, fopen()과 malloc() 모두 같은 방식으로 실패를 알린다는 공통점이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 지나치게 큰 메모리를 요청해 malloc()이 실패하는 상황을 의도적으로 재현한 예제가 NULL 체크의 실전 필요성을 직접 보여준다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The same NULL-check pattern applying to both file access and memory allocation (C):
|
||||
```c
|
||||
// File access failure
|
||||
FILE *fptr = fopen("nothing.txt", "r");
|
||||
if (fptr == NULL) { printf("Could not open file.\n"); return 1; }
|
||||
|
||||
// Memory allocation failure
|
||||
int *numbers = (int*) malloc(100000000000000 * sizeof(int));
|
||||
if (numbers == NULL) { printf("Memory allocation failed.\n"); return 1; }
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Macros]], [[C Memory Deallocate]], [[C Error Handling]], [[C Newline]]
|
||||
- **참조 맥락:** NULL — 줄바꿈(Newline) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C NULL — https://www.w3schools.com/c/c_null.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C NULL" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
id: c-operators
|
||||
title: "C Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["operator categories", "C 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The chapter's own chained example — `sum1 = 100 + 50; sum2 = sum1 + 250; sum3 = sum2 + sum2;` — demonstrates that `+` works identically whether combining two literals, a variable and a literal, or two variables, establishing early that C operators operate on VALUES regardless of whether those values come from literals or variable lookups. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Operator** — performs an operation on variables and/or values. [S1]
|
||||
- **Five operator categories** — Arithmetic, Assignment, Comparison, Logical, and Bitwise (marked "advanced"). [S1]
|
||||
- **Uniform operand handling** — the same operator (e.g. `+`) works on literal-literal, variable-literal, and variable-variable combinations identically. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Chained addition using literals and variables interchangeably: `int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 = sum2 + sum2;` — evaluates to 150, 400, 800. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 챕터가 제시하는 5개 연산자 분류가 이후 각 챕터(산술/대입/비교/논리/비트) 학습의 로드맵 역할을 한다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The + operator working uniformly across literals, a variable+literal, and variable+variable (C):
|
||||
```c
|
||||
int sum1 = 100 + 50; // 150 (100 + 50)
|
||||
int sum2 = sum1 + 250; // 400 (150 + 250)
|
||||
int sum3 = sum2 + sum2; // 800 (400 + 400)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Fixed Width Ints]], [[C Operators Arithmetic]]
|
||||
- **참조 맥락:** 연산자 섹션 개관 — 산술 연산자(Operators Arithmetic) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Operators — https://www.w3schools.com/c/c_operators.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-operators-arithmetic
|
||||
title: "C Arithmetic Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["integer division", "increment decrement", "C 산술 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "arithmetic"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators_arithmetic.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Arithmetic Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Dividing two `int` values ALWAYS produces an `int` result, silently truncating any decimal — `10 / 3` gives `3`, not `3.33` — and the ONLY way to get a decimal result is to make at least the operand types `float`/`double` (`10.0 / 3` gives `3.333...`), meaning integer division isn't a rounding behavior to configure, it's an unavoidable consequence of the operand types chosen. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Seven core arithmetic operators** — `+` (add), `-` (subtract), `*` (multiply), `/` (divide), `%` (modulus/remainder), `++` (increment), `--` (decrement). [S1]
|
||||
- **Integer division truncation** — dividing two `int`s always yields an `int`, discarding any decimal remainder; use `float`/`double` operands to get a decimal result. [S1]
|
||||
- **Increment/decrement round-trip** — incrementing then decrementing the same variable (or vice versa) returns it to its original value. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- All seven operators demonstrated together: `int x = 10; int y = 3; x + y; // 13`, `x - y; // 7`, `x * y; // 30`, `x / y; // 3`, `x % y; // 1`, plus `++z`/`--z` on a separate variable. [S1]
|
||||
- Integer vs decimal division contrast: `int a = 10; int b = 3; printf("%d\n", a / b); // 3 (integer division)` versus `double c = 10.0; double d = 3.0; printf("%f\n", c / d); // 3.333...`. [S1]
|
||||
- Real-life counting example: `int peopleInRoom = 0; peopleInRoom++; peopleInRoom++; peopleInRoom++; // 3 people enter, count = 3` then `peopleInRoom--; // 1 leaves, count = 2`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **정수 나눗셈의 소수점 절삭**: int끼리 나누면 항상 int 결과가 나와 소수점이 버려진다는 점이 명시되며, 소수 결과를 원하면 최소 한쪽을 float/double로 만들어야 한다는 해결책이 함께 제시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
방에 들어오고 나가는 사람 수를 ++/--로 세는 카운터 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Integer division truncates; use float/double operands for a decimal result (C):
|
||||
```c
|
||||
int a = 10;
|
||||
int b = 3;
|
||||
printf("%d\n", a / b); // Integer division, result is 3
|
||||
|
||||
double c = 10.0;
|
||||
double d = 3.0;
|
||||
printf("%f\n", c / d); // Decimal division, result is 3.333...
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators]], [[C Operators Assignment]]
|
||||
- **참조 맥락:** 산술 연산자 — 대입 연산자(Operators Assignment) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Arithmetic Operators — https://www.w3schools.com/c/c_operators_arithmetic.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Arithmetic Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-operators-assignment
|
||||
title: "C Assignment Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["+= -= *=", "compound assignment", "C 대입 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "assignment"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators_assignment.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Assignment Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Every compound assignment operator — including the bitwise ones (`&=`, `|=`, `^=`, `>>=`, `<<=`) covered later in the Bitwise chapter — follows the identical expansion pattern `x OP= y` ≡ `x = x OP y`, meaning learning this ONE rule (rather than memorizing 11 separate operators) is enough to understand every assignment shorthand in the language, arithmetic or bitwise alike. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`=`** — basic assignment. [S1]
|
||||
- **Arithmetic compound operators** — `+=`, `-=`, `*=`, `/=`, `%=`, each expanding to `x = x <op> value`. [S1]
|
||||
- **Bitwise compound operators** — `&=`, `|=`, `^=`, `>>=`, `<<=`, following the SAME expansion pattern as the arithmetic ones. [S1]
|
||||
- **Purpose** — pure shorthand for readability/brevity; functionally identical to the fully-spelled-out form. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Full expansion table: `x += 3` ≡ `x = x + 3`; `x -= 3` ≡ `x = x - 3`; `x *= 3` ≡ `x = x * 3`; `x /= 3` ≡ `x = x / 3`; `x %= 3` ≡ `x = x % 3`; `x &= 3` ≡ `x = x & 3`; `x |= 3` ≡ `x = x | 3`; `x ^= 3` ≡ `x = x ^ 3`; `x >>= 3` ≡ `x = x >> 3`; `x <<= 3` ≡ `x = x << 3`. [S1]
|
||||
- Real-life savings tracker: `int savings = 100; savings += 50; // add 50 to savings printf("Total savings: %d\n", savings);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
저축액에 50을 더하는 savings += 50 예제가 원문에서 직접 실전 활용 사례로 제시됨(계좌 잔액 누적 갱신). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Tracking a running total using the compound addition-assignment operator (C):
|
||||
```c
|
||||
int savings = 100;
|
||||
savings += 50; // add 50 to savings
|
||||
printf("Total savings: %d\n", savings);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators Arithmetic]], [[C Operators Comparison]], [[C Bitwise Operators]]
|
||||
- **참조 맥락:** 대입 연산자 — 비교 연산자(Operators Comparison) 챕터로 이어짐, 비트 대입 연산자는 Bitwise Operators 챕터와 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Assignment Operators — https://www.w3schools.com/c/c_operators_assignment.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Assignment Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-operators-comparison
|
||||
title: "C Comparison Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["== != > <", "boolean 1 or 0", "C 비교 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "comparison"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators_comparison.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Comparison Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Unlike languages with a dedicated `bool`/`Boolean` type, C's comparison operators return plain INTEGERS — `1` for true, `0` for false — meaning the result of `x > y` can be printed with `%d` just like any other int, stored in an `int` variable, and used in arithmetic, because C has no separate boolean type at this point in the tutorial; true/false IS just 1/0. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Six comparison operators** — `==` (equal), `!=` (not equal), `>` (greater than), `<` (less than), `>=` (greater or equal), `<=` (less or equal). [S1]
|
||||
- **Integer return value** — every comparison returns `1` (true) or `0` (false), printable with `%d`. [S1]
|
||||
- **Practical decision-making use** — comparisons are the mechanism for finding answers and making decisions in a program, foreshadowing the upcoming if/else chapters. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic greater-than check: `int x = 5; int y = 3; printf("%d", x > y); // returns 1 (true)`. [S1]
|
||||
- Voting age eligibility check: `int age = 18; printf("%d\n", age >= 18); // 1 (true) printf("%d\n", age < 18); // 0 (false)`. [S1]
|
||||
- Password length check: `int passwordLength = 5; printf("%d\n", passwordLength >= 8); // 0 (false), too short`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **비교 결과는 진짜 정수형**: 별도의 불리언 타입 없이 비교 연산 결과가 그냥 1 또는 0인 정수로 반환된다는 점이 명시되며, 이는 이후 Booleans 챕터에서 더 자세히 다뤄질 예정임이 언급됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
투표 가능 연령 확인(age >= 18)과 비밀번호 길이 확인(passwordLength >= 8)이 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Comparison operators returning plain integers (1 or 0), used for real-world eligibility checks (C):
|
||||
```c
|
||||
int age = 18;
|
||||
printf("%d\n", age >= 18); // 1 (true), old enough to vote
|
||||
printf("%d\n", age < 18); // 0 (false)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators Assignment]], [[C Operators Logical]], [[C Booleans]]
|
||||
- **참조 맥락:** 비교 연산자 — 논리 연산자(Operators Logical) 챕터로 이어짐, 불리언(Booleans) 챕터와 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Comparison Operators — https://www.w3schools.com/c/c_operators_comparison.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Comparison Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-operators-logical
|
||||
title: "C Logical Operators"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["&& || !", "logical AND OR NOT", "C 논리 연산자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "logical"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators_logical.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Logical Operators]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The login-check example combines a comparison-like value (`isLoggedIn`) with its NEGATION (`!isAdmin`) inside a single `&&` expression (`isLoggedIn && !isAdmin` = "regular user") — showing that logical operators aren't just for combining two independent conditions, but are routinely used to express compound business rules like "authenticated AND NOT privileged" as one evaluable expression. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`&&` (AND)** — returns 1 only if BOTH operands are true. [S1]
|
||||
- **`||` (OR)** — returns 1 if AT LEAST ONE operand is true. [S1]
|
||||
- **`!` (NOT)** — reverses the result: 1 becomes 0, 0 becomes 1. [S1]
|
||||
- **1 = true, 0 = false** — the same convention as Comparison Operators; logical operators combine these int-valued truth results. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Login/permission check combining AND and NOT: `int isLoggedIn = 1; int isAdmin = 0; printf("Regular user: %d\n", isLoggedIn && !isAdmin); printf("Has access: %d\n", isLoggedIn || isAdmin); printf("Not logged in: %d\n", !isLoggedIn);` — outputs `1`, `1`, `0` respectively. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
로그인 여부와 관리자 권한을 조합해 "일반 사용자인지", "접근 권한이 있는지"를 판단하는 예제가 원문에서 직접 실전 활용 사례로 제시됨(인증/인가 로직의 기초). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Combining AND and NOT to express a compound access-control rule (C):
|
||||
```c
|
||||
int isLoggedIn = 1;
|
||||
int isAdmin = 0;
|
||||
printf("Regular user: %d\n", isLoggedIn && !isAdmin); // 1
|
||||
printf("Has access: %d\n", isLoggedIn || isAdmin); // 1
|
||||
printf("Not logged in: %d\n", !isLoggedIn); // 0
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators Comparison]], [[C Bitwise Operators]], [[C Conditions Logical]]
|
||||
- **참조 맥락:** 논리 연산자 — 비트 연산자(Bitwise Operators) 챕터로 이어짐, 조건문의 논리 연산(Conditions Logical) 챕터와 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Logical Operators — https://www.w3schools.com/c/c_operators_logical.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Logical Operators" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: c-operators-precedence
|
||||
title: "C Operator Precedence"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["order of operations", "parentheses precedence", "C 연산자 우선순위"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "operators", "precedence"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_operators_precedence.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Operator Precedence]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Same-precedence operators like `+` and `-` are evaluated strictly LEFT TO RIGHT, not right-to-left or by some other rule — `10 - 2 + 5` equals `(10 - 2) + 5 = 13`, not `10 - (2 + 5) = 3` — meaning precedence alone doesn't fully determine evaluation order for operators at the same tier; associativity direction matters too, and parentheses are the only reliable way to override either. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Precedence hierarchy (highest to lowest)** — `()` parentheses → `*`/`/`/`%` → `+`/`-` → comparison (`>`,`<`,`>=`,`<=`) → equality (`==`,`!=`) → `&&` → `||` → `=`. [S1]
|
||||
- **Multiplication before addition** — `2 + 3 * 4` evaluates the `*` first, giving `14`, not `20`. [S1]
|
||||
- **Parentheses override precedence entirely** — `(2 + 3) * 4` forces the addition first, giving `20`. [S1]
|
||||
- **Left-to-right associativity for same-tier operators** — `10 - 2 + 5` evaluates as `(10 - 2) + 5 = 13` since `-` and `+` share the same precedence tier and are evaluated left to right. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Precedence demonstration: `int result1 = 2 + 3 * 4; // 2 + 12 = 14` versus `int result2 = (2 + 3) * 4; // 5 * 4 = 20`. [S1]
|
||||
- Left-to-right associativity demonstration: `int result1 = 10 - 2 + 5; // (10 - 2) + 5 = 13` versus `int result2 = 10 - (2 + 5); // 10 - 7 = 3`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **동일 우선순위 연산자의 결합 방향**: +와 -가 같은 우선순위 등급이라도 왼쪽에서 오른쪽으로 순서대로 계산된다는 점이 별도로 확인되며, 괄호 없이는 이 순서를 바꿀 수 없다는 것이 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 계산 순서가 애매할 때 항상 괄호를 사용하라는 권고가 이 챕터 전체를 관통하는 실전 원칙이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Same-precedence operators evaluate strictly left to right unless parentheses override it (C):
|
||||
```c
|
||||
int result1 = 10 - 2 + 5; // (10 - 2) + 5 = 13
|
||||
int result2 = 10 - (2 + 5); // 10 - 7 = 3
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Bitwise Operators]], [[C Strings]]
|
||||
- **참조 맥락:** 연산자 섹션 마지막 — 문자열(Strings) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Operator Precedence — https://www.w3schools.com/c/c_operators_precedence.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Operator Precedence" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: c-organize-code
|
||||
title: "C Organize Code"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["header files", "include guard", "modular programming", "C 코드 조직화"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "header-files", "modular-programming"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_organize_code.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Organize Code]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The `#ifndef`/`#define`/`#endif` include guard exists to solve a problem that's invisible in small single-file programs but inevitable in multi-file ones — preventing the SAME header from being included twice (directly or transitively through other headers) which would otherwise cause duplicate-declaration compile errors, making the include guard a defensive pattern every C header should carry regardless of whether the problem has actually occurred yet. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Modular programming** — splitting code into smaller, reusable `.c`/`.h` file pairs for readability, maintainability, and debuggability; optional for small programs, valuable for larger ones. [S1]
|
||||
- **Header files (`.h`)** — declare functions, share variables/constants/macros across files, and organize code into logical modules; typically contain declarations, macros, and struct definitions (not full function bodies). [S1]
|
||||
- **Include guard (`#ifndef`/`#define`/`#endif`)** — prevents a header from being included more than once by accident, avoiding duplicate-declaration errors; a standard, recommended practice in every C header. [S1]
|
||||
- **Separation of declaration and definition** — the `.h` file declares function signatures; the corresponding `.c` file provides the actual function bodies. [S1]
|
||||
- **Multi-file compilation** — the compiler must be given ALL relevant `.c` files at once (e.g. `gcc main.c calc.c -o program`) to link them into one executable. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Header file with include guard: `#ifndef CALC_H #define CALC_H int add(int x, int y); int subtract(int x, int y); #endif` (calc.h). [S1]
|
||||
- Corresponding source file: `#include "calc.h" int add(int x, int y) { return x + y; } int subtract(int x, int y) { return x - y; }` (calc.c). [S1]
|
||||
- Consuming the module: `#include <stdio.h> #include "calc.h" int main() { printf("5 + 5 = %d\n", add(5, 5)); printf("6 - 4 = %d\n", subtract(6, 4)); return 0; }` (main.c). [S1]
|
||||
- Compiling multiple files together: `gcc main.c calc.c -o program`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **include guard의 필요성**: 작은 프로그램에서는 문제가 드러나지 않지만, 헤더가 여러 파일에서 직간접적으로 중복 포함될 경우 중복 선언 에러가 발생할 수 있어 모든 C 헤더에 include guard를 넣는 것이 표준 관행으로 권장됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — calc.h/calc.c/main.c로 나눈 계산기 모듈 예제가 여러 파일로 나뉜 프로그램을 gcc로 함께 컴파일하는 실전 워크플로우를 그대로 보여준다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A header file with an include guard, plus the gcc command to compile the multi-file project (C):
|
||||
```c
|
||||
// calc.h
|
||||
#ifndef CALC_H
|
||||
#define CALC_H
|
||||
int add(int x, int y);
|
||||
int subtract(int x, int y);
|
||||
#endif
|
||||
```
|
||||
```bash
|
||||
gcc main.c calc.c -o program
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Comments]], [[C Functions]], [[C Variables]]
|
||||
- **참조 맥락:** Basics 섹션 마지막 — 변수(Variables) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Organize Code — https://www.w3schools.com/c/c_organize_code.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Organize Code" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-output
|
||||
title: "C Output (Print Text)"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["printf", "C 출력"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "output", "printf"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_output.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Output (Print Text)]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`printf()` never adds a trailing newline automatically — three consecutive `printf()` calls in the source's example all render on the SAME line with no separation, meaning C output concatenation is entirely the programmer's responsibility, unlike languages whose default print function appends a newline by convention. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`printf()`** — the standard function for printing text to the screen. [S1]
|
||||
- **Double-quote requirement** — text to print must be wrapped in `""`; omitting the quotes causes a compile error. [S1]
|
||||
- **No automatic newline** — calling `printf()` multiple times concatenates all output onto one line unless the programmer explicitly inserts a newline (covered in the next chapter). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic print: `printf("Hello World!");`. [S1]
|
||||
- Quote requirement demonstrated by contrast: `printf("This sentence will work!");` versus the error-producing `printf(This sentence will produce an error.);`. [S1]
|
||||
- Newline-less concatenation: `printf("Hello World!"); printf("I am learning C."); printf("And it is awesome!");` — all three render on one continuous line. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **printf()는 줄바꿈을 자동 삽입하지 않음**: 세 개의 printf() 호출 결과가 모두 한 줄에 이어져 출력된다는 점이 직접 예시로 증명되며, 줄바꿈을 원한다면 별도로 처리해야 함이 다음 챕터로 예고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 여러 printf() 호출을 한 줄에 이어붙이는 특성을 이해하는 것이 다음 챕터(줄바꿈)로 넘어가는 실전 동기가 된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Multiple printf() calls concatenating onto one line with no automatic newline (C):
|
||||
```c
|
||||
#include <stdio.h>
|
||||
int main() {
|
||||
printf("Hello World!");
|
||||
printf("I am learning C.");
|
||||
printf("And it is awesome!");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Statements]], [[C Comments]], [[C Newline]]
|
||||
- **참조 맥락:** 텍스트 출력 기초 — 주석(Comments) 챕터로 이어짐, 줄바꿈(Newline) 챕터와 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Output (Print Text) — https://www.w3schools.com/c/c_output.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Output (Print Text)" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-pointer-to-pointer
|
||||
title: "C Pointer to Pointer"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["double pointer", "int**", "C 포인터의 포인터"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "pointers", "double-pointer"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_pointer_to_pointer.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Pointer to Pointer]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source's own analogy nails the concept exactly: "a normal pointer is like a note with an address on it; a pointer to pointer is like another note telling you where that first note is kept" — meaning `**pptr` isn't some special new operation, it's just applying the SAME dereference (`*`) operator TWICE in a row, following one address to find a second address, then following that to find the actual value. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Pointer to pointer (double pointer, `int **pptr`)** — a pointer whose stored value is the ADDRESS OF ANOTHER POINTER, not a regular variable. [S1]
|
||||
- **One extra level of indirection** — `*ptr` gives a variable's value directly; `**pptr` gives the same value by following TWO addresses in sequence (pptr → ptr → myNum). [S1]
|
||||
- **Mutability through both levels** — assigning through `**pptr = 20;` changes the ORIGINAL variable (`myNum`), just as `*ptr = 20;` would. [S1]
|
||||
- **Use cases** — passing pointers into functions (so the function can modify what a pointer points to) and working with complex/nested data structures. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Declaring and reading through two levels: `int myNum = 10; int *ptr = &myNum; int **pptr = &ptr; printf("**pptr = %d\n", **pptr); // 10`. [S1]
|
||||
- Modifying the original variable through the double pointer: `int myNum = 5; int *ptr = &myNum; int **pptr = &ptr; **pptr = 20; printf("myNum = %d\n", myNum); // 20`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 함수에 포인터를 전달해 그 포인터 자체를 함수 안에서 바꿔야 할 때, 그리고 복잡한 자료구조를 다룰 때 포인터의 포인터가 유용하다고 원문에 명시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Modifying the original variable through two levels of pointer indirection (C):
|
||||
```c
|
||||
int myNum = 5;
|
||||
int *ptr = &myNum;
|
||||
int **pptr = &ptr;
|
||||
**pptr = 20; // changes myNum
|
||||
printf("myNum = %d\n", myNum); // prints 20
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Pointers Arrays]], [[C Memory Access]], [[C Functions Pointers]]
|
||||
- **참조 맥락:** 포인터의 포인터 — 동적 메모리 접근(Memory Access) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Pointer to Pointer — https://www.w3schools.com/c/c_pointer_to_pointer.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Pointer to Pointer" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-pointers
|
||||
title: "C Pointers"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["pointer declaration", "dereference operator", "C 포인터"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "pointers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_pointers.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Pointers]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The `*` symbol does two OPPOSITE jobs depending on where it appears — in a declaration (`int* ptr`) it CREATES a pointer, but everywhere else (`*ptr`) it DEREFERENCES one to retrieve the pointed-to value — and the source explicitly flags this dual meaning as a common source of confusion, since the same character means "this variable will hold an address" in one context and "give me what's at this address" in another. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Pointer** — a variable that stores another variable's memory address as its value. [S1]
|
||||
- **Type-matched declaration** — a pointer's declared type must match the type of variable it points to (`int* ptr` for an `int`). [S1]
|
||||
- **`*` in declaration vs. elsewhere** — `int* ptr;` creates a pointer variable; `*ptr` (outside declaration) dereferences it to get the pointed-to value. [S1]
|
||||
- **Two equivalent declaration styles** — `int* myNum;` and `int *myNum;` are functionally identical; spacing around `*` is purely stylistic. [S1]
|
||||
- **Why pointers matter** — enable direct memory manipulation (reducing code, improving performance), are essential for implementing data structures (lists, trees, graphs), and are sometimes REQUIRED (e.g. file I/O, memory management). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Creating a pointer and reading the address it stores: `int myAge = 43; int* ptr = &myAge; printf("%p\n", ptr); // same address as &myAge`. [S1]
|
||||
- Dereferencing to get the pointed-to value: `printf("%d\n", *ptr); // 43 (myAge's value, accessed via the pointer)`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **`*`의 이중 의미**: 선언에서 쓰인 int* ptr는 포인터 변수를 만들지만, 선언이 아닌 곳에서 쓰인 *ptr는 역참조 연산자로 동작한다는 점이 혼동 요소로 명시적으로 지적됨. [S1]
|
||||
- **포인터 취급 시 주의사항**: 다른 메모리 주소에 저장된 데이터를 손상시킬 수 있으므로 포인터는 신중하게 다뤄야 한다고 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 리스트/트리/그래프 같은 자료구조를 구현하거나 파일 및 메모리 관리 작업을 할 때 포인터가 필수적으로 쓰인다고 원문에서 직접 언급됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Creating a pointer, then reading the address vs. the dereferenced value (C):
|
||||
```c
|
||||
int myAge = 43; // Variable declaration
|
||||
int* ptr = &myAge; // Pointer declaration
|
||||
printf("%p\n", ptr); // Reference: memory address of myAge
|
||||
printf("%d\n", *ptr); // Dereference: value of myAge (43)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Memory Address]], [[C Pointers Arithmetic]]
|
||||
- **참조 맥락:** 포인터 기초 — 포인터 연산(Pointers Arithmetic) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Pointers — https://www.w3schools.com/c/c_pointers.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Pointers" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,75 @@
|
||||
---
|
||||
id: c-pointers-arithmetic
|
||||
title: "C Pointer Arithmetic"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["pointer increment", "pointer subtraction", "type-scaled pointer movement", "C 포인터 연산"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "pointers", "pointer-arithmetic"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_pointers_arithmetic.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Pointer Arithmetic]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Adding `1` to a pointer never means "move forward by 1 byte" — it means "move forward by the SIZE of whatever type the pointer points to" — so from the same starting address, `int* + 1` jumps 4 bytes while `char* + 1` jumps only 1 byte, meaning pointer arithmetic is silently type-scaled, and mixing up pointer types is explicitly called out as a common mistake that lands you at the wrong memory location entirely. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Pointer arithmetic** — changing a pointer's VALUE to make it reference a different element, exploiting the fact that array elements sit contiguously in memory. [S1]
|
||||
- **`++`/`--`/`+=`/`-=` on pointers** — move the pointer forward/backward by one (or N) elements, just like a loop counter. [S1]
|
||||
- **Type-scaled movement** — `p + 1` advances by `sizeof(pointed-to type)` bytes, not literally 1 byte; an `int*` moves 4 bytes per step while a `char*` moves 1 byte per step. [S1]
|
||||
- **Pointer subtraction (distance)** — subtracting two pointers INTO THE SAME ARRAY yields the number of ELEMENTS between them, not bytes; only valid when both pointers reference the same array. [S1]
|
||||
- **Pointer-driven loop** — looping by incrementing the pointer itself (`p++`) instead of indexing (`myNumbers[i]`) needs no separate index variable at all. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Accessing array elements via pointer offset: `int myNumbers[4] = {25, 50, 75, 100}; int *p = myNumbers; printf("%d\n", *p); printf("%d\n", *(p + 1)); // 50`. [S1]
|
||||
- Moving a pointer with increment/decrement/step: `p++; // next element p--; // previous element p += 2; // jump 2 elements`. [S1]
|
||||
- Pointer subtraction giving element count: `int *start = &myNumbers[1]; int *end = &myNumbers[4]; printf("%ld\n", end - start); // 3 elements apart`. [S1]
|
||||
- Type-dependent step size proven side by side: `int *pi = myNumbers; // moves by sizeof(int), typically 4 bytes char *pc = letters; // moves by 1 byte`. [S1]
|
||||
- Pointer-only loop (no index variable): `int *p = myNumbers; for (int i = 0; i < 4; i++) { printf("%d\n", *p); p++; }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **포인터 이동은 타입에 따라 크기가 다름**: int*는 한 칸 이동 시 보통 4바이트, char*는 1바이트만 이동한다는 점이 동일한 시작 주소에서 직접 비교되어 확인되며, 타입을 혼동하면 잘못된 메모리 위치를 가리키게 된다고 경고됨. [S1]
|
||||
- **배열 경계를 벗어나는 이동 금지**: 배열의 끝을 한 칸 넘어선 위치까지는 포인터 비교용으로만 안전하며, 그 값을 실제로 역참조해서는 안 된다는 점이 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 인덱스 변수 없이 포인터 자체를 증가시키며 배열을 순회하는 방식이 메모리를 직접 다루는 실전 코드에서 흔히 쓰이는 패턴으로 소개됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Looping through an array by advancing the pointer itself, with no index variable (C):
|
||||
```c
|
||||
int myNumbers[4] = {25, 50, 75, 100};
|
||||
int *p = myNumbers; // start of array
|
||||
for (int i = 0; i < 4; i++) {
|
||||
printf("%d\n", *p);
|
||||
p++; // move to next element
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Pointers]], [[C Pointers Arrays]]
|
||||
- **참조 맥락:** 포인터 연산 — 포인터와 배열(Pointers Arrays) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Pointer Arithmetic — https://www.w3schools.com/c/c_pointers_arithmetic.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Pointer Arithmetic" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-pointers-arrays
|
||||
title: "C Pointers and Arrays"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["array name as pointer", "array-pointer equivalence", "C 포인터와 배열"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "pointers", "arrays"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_pointers_arrays.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Pointers and Arrays]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
An array's NAME already IS a pointer to its first element — proven directly by printing `myNumbers` and `&myNumbers[0]` and getting the IDENTICAL address — meaning `*myNumbers` (dereferencing the bare array name) works exactly like `myNumbers[0]`, and the entire array-indexing syntax `arr[i]` is really syntactic sugar over pointer arithmetic (`*(arr + i)`) that's been running underneath the whole time. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Array name = pointer to first element** — `myNumbers` and `&myNumbers[0]` evaluate to the exact same address. [S1]
|
||||
- **`*arrayName`** — dereferences the array's implicit pointer to get the FIRST element's value, equivalent to `arrayName[0]`. [S1]
|
||||
- **`*(arrayName + i)`** — equivalent to `arrayName[i]`; offsetting the array-as-pointer by `i` and dereferencing reaches the same element as bracket indexing. [S1]
|
||||
- **Mutation via dereference** — `*myNumbers = 13;` changes the first element just like `myNumbers[0] = 13;` would. [S1]
|
||||
- **Element memory layout confirms the size math** — consecutive `int` elements' addresses differ by exactly `sizeof(int)` (4 bytes), so an array of 4 ints occupies 16 bytes total. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Proving array-name-equals-pointer: `printf("%p\n", myNumbers); printf("%p\n", &myNumbers[0]); // identical addresses`. [S1]
|
||||
- Dereferencing the bare array name for the first element: `printf("%d", *myNumbers); // 25 (same as myNumbers[0])`. [S1]
|
||||
- Offsetting to reach later elements: `printf("%d\n", *(myNumbers + 1)); // 50 printf("%d", *(myNumbers + 2)); // 75`. [S1]
|
||||
- Mutating through dereference: `*myNumbers = 13; *(myNumbers + 1) = 17;` changes the first and second elements. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **배열 이름은 이미 포인터**: 배열 이름을 그대로 출력한 주소와 &배열[0]으로 얻은 주소가 완전히 동일하다는 점이 직접 증명되며, 이는 배열 인덱싱(arr[i])이 실제로는 포인터 연산(*(arr+i))의 편의 문법임을 시사함. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
대용량 배열이나 2차원 배열, 그리고 배열인 문자열(string)에 접근할 때 포인터 방식이 더 효율적이고 빠르다는 점이 원문에서 직접 언급됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
An array's name and the address of its first element are identical (C):
|
||||
```c
|
||||
int myNumbers[4] = {25, 50, 75, 100};
|
||||
printf("%p\n", myNumbers); // e.g. 0x7ffe70f9d8f0
|
||||
printf("%p\n", &myNumbers[0]); // same address: 0x7ffe70f9d8f0
|
||||
printf("%d", *myNumbers); // 25, same as myNumbers[0]
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Pointers Arithmetic]], [[C Pointer To Pointer]], [[C Arrays Multi]]
|
||||
- **참조 맥락:** 포인터와 배열의 관계 — 포인터의 포인터(Pointer To Pointer) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Pointers and Arrays — https://www.w3schools.com/c/c_pointers_arrays.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Pointers and Arrays" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,78 @@
|
||||
---
|
||||
id: c-random-numbers
|
||||
title: "C Random Numbers"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["rand() srand()", "seeding random", "dice roll example", "C 난수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "random", "stdlib"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_random_numbers.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Random Numbers]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Without calling `srand()`, `rand()` produces the EXACT SAME sequence of numbers every single time the program runs — it's not "random" by default at all, just deterministic-looking — and the standard fix (seeding with `time(NULL)`) works only because the current time is itself always different, meaning C's "randomness" is really pseudo-randomness bootstrapped from an ever-changing external value. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`rand()`** (from `<stdlib.h>`) — returns a random integer, but deterministic/repeatable unless seeded. [S1]
|
||||
- **`srand(seed)`** — sets the starting point for `rand()`'s sequence; without it, the sequence repeats identically on every run. [S1]
|
||||
- **Time as a seed** — `srand(time(NULL))` (requiring `<time.h>`) uses the current time as the seed since it's always changing, producing different sequences run to run. [S1]
|
||||
- **Call `srand()` exactly once** — specifically at the start of `main()`, NOT repeatedly inside a loop (re-seeding inside a loop would reset the sequence and undermine randomness). [S1]
|
||||
- **Range restriction via modulo** — `rand() % N` maps the result into the range `0` to `N-1`; adding an offset shifts the range further (e.g. `(rand() % 6) + 1` for 1-6). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Unseeded rand() (repeats every run): `int r = rand(); printf("%d\n", r);`. [S1]
|
||||
- Properly seeded rand(): `srand(time(NULL)); printf("%d\n", rand());` — different results each run. [S1]
|
||||
- Restricting to a 0-9 range: `int x = rand() % 10; // 0..9`. [S1]
|
||||
- Dice-roll simulation combining modulo and offset: `int dice1 = (rand() % 6) + 1; int dice2 = (rand() % 6) + 1; printf("You rolled %d and %d (total = %d)\n", dice1, dice2, dice1 + dice2);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **시드 없이는 진짜 랜덤이 아님**: srand()를 호출하지 않으면 프로그램을 몇 번을 실행해도 항상 같은 숫자가 나온다는 점이 명시적으로 경고됨 — 진짜 다른 결과를 원하면 반드시 시드를 설정해야 함. [S1]
|
||||
- **srand()는 반복문 안에서 재호출 금지**: main 시작 시 딱 한 번만 호출해야 하며, 루프 안에서 반복 호출하면 안 된다는 점이 팁으로 강조됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
주사위 두 개를 굴려 1-6 범위의 숫자를 뽑고 합계를 계산하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Simulating a dice roll using rand(), modulo, and an offset (C):
|
||||
```c
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
int main() {
|
||||
srand(time(NULL)); // seed once, with the current time
|
||||
int dice1 = (rand() % 6) + 1;
|
||||
int dice2 = (rand() % 6) + 1;
|
||||
printf("You rolled %d and %d (total = %d)\n", dice1, dice2, dice1 + dice2);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Math]], [[C Date Time]], [[C Booleans]]
|
||||
- **참조 맥락:** 수학 및 난수 섹션 마지막 — 불리언(Booleans) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Random Numbers — https://www.w3schools.com/c/c_random_numbers.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Random Numbers" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: c-scope
|
||||
title: "C Variable Scope"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["local scope", "global scope", "shadowing", "C 변수 스코프"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "scope"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_scope.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Variable Scope]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
When a local variable shares a name with a global variable, C doesn't merge or conflict them — it silently treats them as TWO COMPLETELY SEPARATE variables, and the source's own example proves it: the function prints its local `x` (22) while `main()` prints the untouched global `x` (5), meaning name collision between scopes causes no error at all, just quiet shadowing that can confuse anyone reading the code without realizing two different `x`s exist. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Scope** — the region of code where a variable is accessible; in C, a variable is only usable within the region it was created. [S1]
|
||||
- **Local scope** — a variable declared INSIDE a function belongs only to that function; using it outside causes a compile error. [S1]
|
||||
- **Global scope** — a variable declared OUTSIDE any function is accessible from ANY scope, both other functions and `main()`. [S1]
|
||||
- **Name collision = shadowing, not conflict** — a local variable with the SAME NAME as a global one creates two independent variables; inside the function, the LOCAL one takes precedence and the global remains untouched. [S1]
|
||||
- **Global mutability risk** — because globals are reachable from anywhere, any function can silently modify one (e.g. `++x`), making the program's state harder to reason about. [S1]
|
||||
- **Recommended practice** — prefer local variables for maintainability; understand globals because they appear often in existing/collaborative C code. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Local variable inaccessible outside its function (produces an error): `void myFunction() { int x = 5; } int main() { myFunction(); printf("%d", x); /* error: x not accessible here */ }`. [S1]
|
||||
- Global variable accessible everywhere: `int x = 5; void myFunction() { printf("%d", x); } int main() { myFunction(); printf("%d", x); }`. [S1]
|
||||
- Same-name shadowing — two independent variables coexist: `int x = 5; void myFunction() { int x = 22; printf("%d\n", x); // 22, local } int main() { myFunction(); printf("%d\n", x); // 5, global — untouched }`. [S1]
|
||||
- A function silently mutating a global: `int x = 5; void myFunction() { printf("%d\n", ++x); } int main() { myFunction(); printf("%d\n", x); } // x is now 6`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **동일 이름의 지역/전역 변수는 충돌이 아니라 완전히 별개의 변수**: 함수 안의 지역 x(22)와 함수 밖의 전역 x(5)가 이름은 같지만 서로 독립적으로 존재하며, 함수 내부에서는 지역 변수가 우선한다는 점이 직접 예제로 증명됨. [S1]
|
||||
- **전역 변수는 어디서든 수정 가능**: 어떤 함수든 전역 변수를 조용히 변경할 수 있으므로 주의해서 다뤄야 한다고 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 기존 C 프로그램이나 협업 코드에서 전역 변수를 마주칠 가능성이 높으므로 스코프 동작 원리를 이해해두는 것이 실전에서 유용하다고 원문에 명시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A local variable shadowing a global variable of the same name (C):
|
||||
```c
|
||||
int x = 5; // global
|
||||
void myFunction() {
|
||||
int x = 22; // local, shadows the global
|
||||
printf("%d\n", x); // 22 (local x)
|
||||
}
|
||||
int main() {
|
||||
myFunction();
|
||||
printf("%d\n", x); // 5 (global x, untouched)
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Functions Inline]], [[C Storage Classes]], [[C User Input]]
|
||||
- **참조 맥락:** 스코프 섹션 유일 챕터 — 사용자 입력(User Input) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Variable Scope — https://www.w3schools.com/c/c_scope.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Variable Scope" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-statements
|
||||
title: "C Statements"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["semicolon", "C 명령문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "statements"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_statements.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Statements]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Forgetting a single semicolon produces a compiler error that points to the WRONG line — the source's own example shows a missing `;` after one `printf()` call raising `error: expected ';' before 'return'`, meaning the compiler flags the token immediately AFTER the missing semicolon rather than the actual offending line, a common beginner confusion worth knowing in advance. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Statement** — one instruction in a C program; the building block of all C code. [S1]
|
||||
- **Mandatory semicolon termination** — every statement must end with `;`; omitting it causes a compile-time error. [S1]
|
||||
- **Sequential execution** — multiple statements in a program execute strictly in the order they are written, one at a time. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Single statement: `printf("Hello World!");`. [S1]
|
||||
- Missing-semicolon error demonstration: `printf("Hello World!")` (no trailing `;`) produces `error: expected ';' before 'return'` — the error references the NEXT statement, not the line actually missing the semicolon. [S1]
|
||||
- Sequential multi-statement execution: `printf("Hello World!"); printf("Have a good day!"); return 0;` — runs top to bottom, printing "Hello World!" then "Have a good day!" before ending. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **에러 메시지의 위치 오프셋**: 세미콜론이 누락된 실제 줄이 아니라 그 다음 토큰(예: return)을 기준으로 에러가 보고된다는 점이 실전 디버깅 시 혼동을 일으킬 수 있다고 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 세미콜론 누락 에러의 위치가 실제 원인과 다르다는 점을 미리 알아두면 실전 디버깅 시간을 단축할 수 있다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Three statements executing sequentially in source order (C):
|
||||
```c
|
||||
printf("Hello World!");
|
||||
printf("Have a good day!");
|
||||
return 0;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Syntax]], [[C Output]]
|
||||
- **참조 맥락:** 명령문과 세미콜론 규칙 — 출력(Output) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Statements — https://www.w3schools.com/c/c_statements.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Statements" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,76 @@
|
||||
---
|
||||
id: c-storage-classes
|
||||
title: "C Storage Classes"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["auto static register extern", "static local variable", "C 저장 클래스"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "storage-classes", "static"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_storage_classes.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Storage Classes]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A `static` local variable inside a function survives BETWEEN separate calls to that function — the source's `count()` example prints `1`, `2`, `3` across three separate calls specifically because `static` makes the variable retain its value instead of resetting to 0 each time, whereas an ordinary local variable would print `1`, `1`, `1` — demonstrating that `static` fundamentally changes a variable's LIFETIME, not just its scope. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Scope vs. storage class** — scope defines WHERE a variable can be used; storage class defines HOW LONG it lasts and WHERE it's stored — two independent concepts. [S1]
|
||||
- **`auto`** — the default storage class for local variables inside functions; rarely written explicitly since it's already the default. [S1]
|
||||
- **`static`** — a local variable keeps its value across separate function calls (rather than resetting each call); a global variable/function marked `static` becomes invisible outside its own file. [S1]
|
||||
- **`register`** — suggests storing a variable in a CPU register for faster access; its address cannot be taken with `&`; considered mostly obsolete since modern compilers auto-optimize register allocation. [S1]
|
||||
- **`extern`** — tells the compiler a variable/function is DEFINED in another file, used for sharing variables across multiple source files. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- `static` preserving value across calls: `void count() { static int myNum = 0; myNum++; printf("num = %d\n", myNum); } int main() { count(); count(); count(); return 0; }` — outputs `num = 1`, `num = 2`, `num = 3` (removing `static` would reset to 1 each time). [S1]
|
||||
- `extern` sharing a variable across files: `main.c` declares `extern int shared;` while `data.c` defines `int shared = 50;`, compiled together via `gcc main.c data.c -o program`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **static은 값을 유지, register는 사실상 구식**: static이 함수 호출 간 값을 보존한다는 점과, register 키워드는 현대 컴파일러가 알아서 최적화하므로 명시적으로 쓸 필요가 거의 없다는 점이 함께 언급됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — count() 함수가 호출될 때마다 값을 누적하는 static 카운터 패턴이 함수 호출 횟수를 추적하는 실전 활용의 대표 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A static local variable retaining its value across separate function calls (C):
|
||||
```c
|
||||
void count() {
|
||||
static int myNum = 0; // Keeps its value between calls
|
||||
myNum++;
|
||||
printf("num = %d\n", myNum);
|
||||
}
|
||||
int main() {
|
||||
count(); // num = 1
|
||||
count(); // num = 2
|
||||
count(); // num = 3
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Constants]], [[C Scope]], [[C Fixed Width Ints]]
|
||||
- **참조 맥락:** 저장 클래스와 변수 생명주기 — 고정폭 정수(Fixed Width Ints) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Storage Classes — https://www.w3schools.com/c/c_storage_classes.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Storage Classes" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-strings
|
||||
title: "C Strings"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["char array", "null terminator", "C 문자열"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "strings"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_strings.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Strings]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
C has no true `String` type at all — a string is just an array of `char`s ending in a special `\0` null-terminator character, proven directly by the fact that `sizeof()` reports the SAME size (13 bytes) whether the string was written as a convenient literal (`"Hello World!"`) or manually spelled out character-by-character with an explicit `\0` at the end (`{'H','e',...,'!','\0'}`) — the literal syntax is pure convenience, not a different underlying type. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **No dedicated String type** — a C "string" is a `char` array; `char greetings[] = "Hello World!";` is the idiomatic way to create one. [S1]
|
||||
- **`%s` format specifier** — used to print an entire string (as opposed to `%c` for a single character). [S1]
|
||||
- **Index access** — since a string is an array, `greetings[0]` accesses its first character, printed with `%c`. [S1]
|
||||
- **Mutable characters** — individual characters can be reassigned via index (`greetings[0] = 'J';`), changing the string in place. [S1]
|
||||
- **Null terminator (`\0`)** — required at the end of a manually-built character-list string; string literals get it added automatically. [S1]
|
||||
- **Loop-through pattern** — iterating a string's characters via a `for` loop, ideally using `sizeof(arr)/sizeof(arr[0])` for the length instead of a hardcoded number. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Modifying a single character: `char greetings[] = "Hello World!"; greetings[0] = 'J'; printf("%s", greetings); // Outputs Jello World!`. [S1]
|
||||
- Manual character-list construction requiring an explicit null terminator: `char greetings[] = {'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};`. [S1]
|
||||
- Proving both construction methods produce identically-sized arrays: `printf("%zu\n", sizeof(greetings)); // 13` and `printf("%zu\n", sizeof(greetings2)); // 13` (literal form auto-adds `\0`). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **문자열 리터럴과 수동 문자 나열의 동등성**: 두 방식 모두 결국 동일한 크기(13바이트, \0 포함)의 char 배열을 만든다는 점이 sizeof 비교로 직접 증명됨 — 리터럴은 단지 \0을 자동으로 추가해주는 편의 문법일 뿐. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
인사말과 이름을 조합해 환영 메시지를 만드는 예제(`"%s %s!", message, fname`)가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Looping through a string's characters using sizeof for a portable length calculation (C):
|
||||
```c
|
||||
char carName[] = "Volvo";
|
||||
int length = sizeof(carName) / sizeof(carName[0]);
|
||||
int i;
|
||||
for (i = 0; i < length; ++i) {
|
||||
printf("%c\n", carName[i]);
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Operators Precedence]], [[C Arrays]], [[C Strings Esc]]
|
||||
- **참조 맥락:** 문자열 섹션 첫 챕터 — 특수문자/이스케이프(Strings Esc) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Strings — https://www.w3schools.com/c/c_strings.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Strings" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
id: c-strings-esc
|
||||
title: "C Special Characters"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["escape characters", "backslash escape", "C 이스케이프 문자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "strings", "escape-characters"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_strings_esc.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Special Characters]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A literal double-quote inside a double-quoted string is fundamentally AMBIGUOUS to the compiler — `"We are the so-called "Vikings" from the north."` looks like three separate adjacent strings, not one string containing quotes — so `\"` isn't just a stylistic escape, it's the only way to disambiguate where the enclosing string actually ends. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **The core problem** — double quotes delimit C strings, so a literal `"` inside one prematurely ends the string as far as the compiler is concerned. [S1]
|
||||
- **Core escape sequences** — `\'` (single quote), `\"` (double quote), `\\` (literal backslash). [S1]
|
||||
- **Other common escapes** — `\n` (newline), `\t` (tab), `\0` (null terminator). [S1]
|
||||
- **Backslash as the universal escape prefix** — turns the following character into a literal string character rather than a syntactic delimiter. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Escaping double quotes inside a string: `char txt[] = "We are the so-called \"Vikings\" from the north.";`. [S1]
|
||||
- Escaping a single quote: `char txt[] = "It\'s alright.";`. [S1]
|
||||
- Escaping a literal backslash: `char txt[] = "The character \\ is called backslash.";`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 큰따옴표가 포함된 인용문(예: "Vikings")을 문자열에 그대로 담아야 할 때 \" 이스케이프가 실전에서 바로 쓰인다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Escaping a literal double quote so it doesn't prematurely end the string (C):
|
||||
```c
|
||||
char txt[] = "We are the so-called \"Vikings\" from the north.";
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Strings]], [[C Strings Functions]]
|
||||
- **참조 맥락:** 이스케이프 문자 — 문자열 함수(Strings Functions) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Special Characters — https://www.w3schools.com/c/c_strings_esc.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Special Characters" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-strings-functions
|
||||
title: "C String Functions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["strlen strcat strcpy strcmp", "string.h", "C 문자열 함수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "strings", "string-functions"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_strings_functions.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C String Functions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`strlen()` and `sizeof()` measure fundamentally different things and diverge sharply once a buffer is oversized — for a 26-letter alphabet stored in a 50-byte array, `strlen()` still correctly reports 26 (it counts up to the `\0`), while `sizeof()` reports 50 (the array's total allocated memory), meaning `sizeof` is NEVER a reliable way to get "string length" once the array is larger than the string it holds. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`<string.h>`** — the header required to use C's built-in string functions. [S1]
|
||||
- **`strlen(str)`** — returns the string's character count UP TO (not including) the `\0` terminator. [S1]
|
||||
- **`sizeof(arr)`** — returns the array's total allocated memory in bytes, INCLUDING the `\0` and any unused trailing space — not the string's actual content length. [S1]
|
||||
- **`strcat(dest, src)`** — appends `src` onto the end of `dest`; `dest`'s buffer must be large enough to hold both strings combined. [S1]
|
||||
- **`strcpy(dest, src)`** — copies `src`'s value into `dest`; `dest`'s buffer must be large enough for the copied content. [S1]
|
||||
- **`strcmp(str1, str2)`** — returns `0` if the strings are equal, a non-zero value otherwise. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- `strlen` vs `sizeof` on an exactly-sized array: `char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; strlen(alphabet) // 26, sizeof(alphabet) // 27` (27 includes `\0`). [S1]
|
||||
- `strlen` vs `sizeof` on an OVERSIZED array — the critical divergence: `char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; strlen(alphabet) // still 26, sizeof(alphabet) // 50` (the array's declared capacity, not content length). [S1]
|
||||
- Concatenation requiring a big-enough destination buffer: `char str1[20] = "Hello "; char str2[] = "World!"; strcat(str1, str2); printf("%s", str1);`. [S1]
|
||||
- Comparison returning 0 for equal strings, non-zero otherwise: `strcmp(str1, str2); // 0 if equal` / `strcmp(str1, str3); // -4 if not equal`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **sizeof는 문자열 길이 측정 도구가 아님**: 배열 크기가 실제 문자열보다 클 경우 sizeof는 할당된 전체 메모리(50)를 반환하지만 strlen은 여전히 실제 내용 길이(26)를 정확히 반환한다는 점이 명시적으로 대비됨 — sizeof를 문자열 길이 측정에 쓰면 안 된다는 강력한 경고. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — strcat으로 "Hello "와 "World!"를 합치는 예제가 문자열 연결의 표준 실전 활용이며, 대상 버퍼 크기를 미리 충분히 확보해야 한다는 주의사항이 함께 강조된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
strlen() and sizeof() diverging once the buffer is larger than the actual string content (C):
|
||||
```c
|
||||
char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
printf("%zu\n", strlen(alphabet)); // 26 (actual content length)
|
||||
printf("%zu\n", sizeof(alphabet)); // 50 (total allocated buffer size)
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Strings Esc]], [[C Data Types Sizeof]], [[C Math]]
|
||||
- **참조 맥락:** 문자열 섹션 마지막 — 수학 함수(Math) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C String Functions — https://www.w3schools.com/c/c_strings_functions.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C String Functions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: c-structs
|
||||
title: "C Structures (structs)"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["struct keyword", "dot syntax", "C 구조체"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "structs"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_structs.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Structures (structs)]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Directly assigning a string literal to a struct's `char[]` member (`s1.myString = "Some text";`) produces a compile ERROR ("assignment to expression with array type") — the exact same restriction from the Strings chapter (arrays can't be reassigned wholesale) applies inside structs too, requiring `strcpy()` UNLESS the assignment happens at declaration time using the comma-separated initializer syntax, which is the one place string literals ARE allowed directly. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Structure (`struct`)** — groups multiple MIXED-type variables ("members") into one unit, unlike arrays which require a single uniform type. [S1]
|
||||
- **Declaration + variable creation** — the `struct Name {...};` block only defines the TEMPLATE; you must separately declare `struct Name variableName;` to create an actual instance. [S1]
|
||||
- **Dot syntax (`.`)** — accesses/assigns individual members (`s1.myNum = 13;`). [S1]
|
||||
- **String members require `strcpy()`** — direct assignment (`s1.myString = "text";`) fails to compile; use `strcpy(s1.myString, "text");` instead. [S1]
|
||||
- **Initializer-list exception** — at DECLARATION time, `struct myStructure s1 = {13, 'B', "Some text"};` allows string literals directly, no `strcpy()` needed — values must be listed in the same order as the members were declared. [S1]
|
||||
- **Struct-to-struct copy** — `s2 = s1;` copies ALL members at once, including string arrays, without needing `strcpy()` per-field. [S1]
|
||||
- **Template reuse** — one struct definition (e.g. `Car`) can be instantiated repeatedly with different values (`car1`, `car2`, `car3`), avoiding separate ad-hoc variable sets per entity. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- The string-assignment error case: `s1.myString = "Some text"; // error: assignment to expression with array type`. [S1]
|
||||
- The `strcpy()` fix: `strcpy(s1.myString, "Some text");`. [S1]
|
||||
- Initializer-list shortcut bypassing `strcpy()`: `struct myStructure s1 = {13, 'B', "Some text"};`. [S1]
|
||||
- Real-life template reuse: `struct Car { char brand[30]; char model[30]; int year; }; struct Car car1 = {"BMW", "X5", 1999}; struct Car car2 = {"Ford", "Mustang", 1969};`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **문자열 멤버 직접 대입 불가**: 구조체 안의 char 배열 멤버에도 배열 챕터와 동일한 제약이 적용되어 strcpy()가 필요하지만, 선언 시 초기화 리스트({...}) 문법에서는 예외적으로 문자열 리터럴을 직접 쓸 수 있다는 점이 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
Car 구조체 하나로 BMW/Ford/Toyota 세 대의 서로 다른 자동차 정보를 저장하는 예제가 원문에서 직접 실전 활용 사례로 제시됨(하나의 템플릿, 여러 인스턴스). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
One struct template reused for multiple distinct real-world entities (C):
|
||||
```c
|
||||
struct Car {
|
||||
char brand[30];
|
||||
char model[30];
|
||||
int year;
|
||||
};
|
||||
int main() {
|
||||
struct Car car1 = {"BMW", "X5", 1999};
|
||||
struct Car car2 = {"Ford", "Mustang", 1969};
|
||||
printf("%s %s %d\n", car1.brand, car1.model, car1.year);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Arrays RealLife]], [[C Strings Functions]], [[C Structs Nested]]
|
||||
- **참조 맥락:** 구조체 섹션 첫 챕터 — 중첩 구조체(Structs Nested) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Structures (structs) — https://www.w3schools.com/c/c_structs.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Structures (structs)" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
id: c-structs-nested
|
||||
title: "C Nested Structures"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["struct inside struct", "layered data", "C 중첩 구조체"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "structs", "nested-structs"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_structs_nested.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Nested Structures]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Accessing a nested struct's member requires CHAINING dot syntax (`car1.owner.firstName`) rather than a single dot — each additional layer of nesting adds one more `.` hop, meaning the access path itself mirrors the data's logical hierarchy exactly (car → owner → firstName), making deeply nested structures self-documenting about their own structure just from how you reach a value. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Nested structure** — a struct that contains ANOTHER struct as one of its members, useful for grouping related data in layers. [S1]
|
||||
- **Chained dot access** — reaching a nested member requires one `.` per layer of nesting (`car1.owner.firstName`, not a shortcut). [S1]
|
||||
- **Composition over flattening** — instead of cramming an owner's first/last name directly into the `Car` struct, a separate `Owner` struct is composed INTO `Car`, keeping each struct focused on one concept. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Defining and nesting: `struct Owner { char firstName[30]; char lastName[30]; }; struct Car { char brand[30]; int year; struct Owner owner; };`. [S1]
|
||||
- Initializing a nested struct by passing an already-built inner struct as one field: `struct Owner person = {"John", "Doe"}; struct Car car1 = {"Toyota", 2010, person};`. [S1]
|
||||
- Chained access to reach the innermost value: `printf("Owner: %s %s\n", car1.owner.firstName, car1.owner.lastName);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
자동차(Car) 구조체 안에 소유자(Owner) 구조체를 중첩시켜 자동차와 소유자 정보를 계층적으로 묶는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Chained dot-access to reach a value inside a nested struct (C):
|
||||
```c
|
||||
struct Owner {
|
||||
char firstName[30];
|
||||
char lastName[30];
|
||||
};
|
||||
struct Car {
|
||||
char brand[30];
|
||||
int year;
|
||||
struct Owner owner; // Nested structure
|
||||
};
|
||||
int main() {
|
||||
struct Owner person = {"John", "Doe"};
|
||||
struct Car car1 = {"Toyota", 2010, person};
|
||||
printf("Owner: %s %s\n", car1.owner.firstName, car1.owner.lastName);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Structs]], [[C Structs Padding]]
|
||||
- **참조 맥락:** 중첩 구조체 — 구조체 정렬/패딩(Structs Padding) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Nested Structures — https://www.w3schools.com/c/c_structs_nested.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Nested Structures" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-structs-padding
|
||||
title: "C Struct Alignment and Padding"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["struct padding", "member reordering", "struct vs union size", "C 구조체 패딩"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "structs", "memory-alignment"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_structs_padding.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Struct Alignment and Padding]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Simply REORDERING a struct's members — with no change to what data it holds — can shrink its total size by a third: the exact same three members (`char`, `int`, `char`) occupy 12 bytes when declared `char, int, char` but only 8 bytes when reordered to `int, char, char`, because the compiler only needs to insert padding to align the LARGEST member (int) once, at the front, instead of bracketing it awkwardly between two chars. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Padding** — extra, unused bytes the compiler inserts between struct members so each member starts at a memory address aligned to its own size (e.g. an `int` starting at a multiple of 4), because aligned reads are faster for the CPU. [S1]
|
||||
- **Size ≠ sum of members** — a struct with 1+4+1=6 bytes of actual data can occupy 12 bytes total once padding is added. [S1]
|
||||
- **Reordering reduces padding** — placing larger members FIRST (before smaller ones) minimizes the total padding needed, shrinking overall struct size. [S1]
|
||||
- **Structs vs unions: no padding in unions** — a union's members all share ONE memory location (sized to the largest member), so there's no padding BETWEEN members, though alignment rules for the shared location itself still apply. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Unpadded-looking struct that's actually 12 bytes: `struct Example { char a; int b; char c; };` — expected 6 bytes, actual 12 (1 + 3 padding + 4 + 1 + 3 padding, so `b` starts at a 4-byte-aligned offset and the total is also a multiple of 4). [S1]
|
||||
- Reordered struct shrinking to 8 bytes: `struct Example { int b; char a; char c; };` — same three members, less padding needed since the int comes first. [S1]
|
||||
- Struct vs union size contrast with identical members: `struct S { char a; int b; char c; };` (12 bytes) versus `union U { char a; int b; char c; };` (4 bytes, sized to the largest member `int`). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **멤버 순서만으로 구조체 크기가 달라짐**: 동일한 세 멤버라도 char-int-char 순서면 12바이트, int-char-char 순서면 8바이트가 된다는 점이 직접 비교로 증명되며, 큰 타입을 앞에 배치하면 패딩을 줄일 수 있다는 실용적 팁으로 이어짐. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
저수준 메모리나 파일 포맷을 다루지 않는 한 이 문제를 신경 쓸 필요는 거의 없다고 원문에 명시되지만, 메모리가 중요한 대규모 프로그램에서는 멤버 순서 재배치로 구조체 크기를 줄이는 것이 실전 최적화 기법으로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Reordering struct members (larger types first) to reduce padding and shrink total size (C):
|
||||
```c
|
||||
// 12 bytes (char, int, char — more padding needed)
|
||||
struct Example { char a; int b; char c; };
|
||||
|
||||
// 8 bytes (int, char, char — less padding needed)
|
||||
struct Example { int b; char a; char c; };
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Structs Nested]], [[C Unions]], [[C Structs Pointers]]
|
||||
- **참조 맥락:** 구조체 정렬/패딩 — 구조체와 포인터(Structs Pointers) 챕터로 이어짐, 유니온(Unions) 챕터와 직접 대비됨.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Struct Alignment and Padding — https://www.w3schools.com/c/c_structs_padding.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Struct Alignment and Padding" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: c-structs-pointers
|
||||
title: "C Structs and Pointers"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["arrow operator", "struct pointer", "C 구조체 포인터"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "structs", "pointers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_structs_pointers.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Structs and Pointers]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Passing a struct pointer into a function is the difference between the function seeing a temporary COPY versus the ORIGINAL — the `updateYear()` example modifies `c->year` inside the function and the change is visible back in `main()` afterward, specifically because a pointer (address) was passed rather than the struct itself, which would have been copied and discarded when the function returned. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`struct Type *ptr`** — declares a pointer to a struct, same `*` syntax as any other pointer type. [S1]
|
||||
- **`->` (arrow operator)** — REPLACES the dot syntax when accessing members through a pointer; `ptr->member` is required instead of `ptr.member`. [S1]
|
||||
- **Function mutation via pointer** — passing `&myCar` (the struct's address) lets a function permanently modify the original struct's members, unlike passing the struct by value. [S1]
|
||||
- **Three motivations for struct pointers** — avoid copying large structs (performance/memory), allow functions to modify the original values, and enable dynamic struct creation via `malloc()` (previewed, covered later in Memory Management). [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic pointer declaration and arrow-operator access: `struct Car car = {"Toyota", 2020}; struct Car *ptr = &car; printf("Brand: %s\n", ptr->brand); printf("Year: %d\n", ptr->year);`. [S1]
|
||||
- Function that mutates the original struct via a pointer parameter: `void updateYear(struct Car *c) { c->year = 2025; } int main() { struct Car myCar = {"Toyota", 2020}; updateYear(&myCar); printf("Year: %d\n", myCar.year); }` — prints 2025, not 2020, because the function received the original struct's address. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **포인터 접근에는 화살표 연산자 필수**: 구조체 변수는 점(.) 문법을 쓰지만, 포인터를 통한 접근은 반드시 화살표(->) 연산자를 써야 한다는 점이 문법적 차이로 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
자동차 구조체의 연식(year)을 함수 안에서 포인터를 통해 2025로 변경하고 그 변경이 main()에도 반영되는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A function permanently modifying the original struct's field via a pointer parameter (C):
|
||||
```c
|
||||
struct Car {
|
||||
char brand[30];
|
||||
int year;
|
||||
};
|
||||
void updateYear(struct Car *c) {
|
||||
c->year = 2025; // Change the year
|
||||
}
|
||||
int main() {
|
||||
struct Car myCar = {"Toyota", 2020};
|
||||
updateYear(&myCar); // Pass a pointer so the function can change the year
|
||||
printf("Year: %d\n", myCar.year); // 2025
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Structs Padding]], [[C Pointers]], [[C Enums]]
|
||||
- **참조 맥락:** 구조체와 포인터 — 열거형(Enums) 챕터로 이어짐, 포인터(Pointers) 챕터와 직접 연결.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Structs and Pointers — https://www.w3schools.com/c/c_structs_pointers.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Structs and Pointers" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: c-switch
|
||||
title: "C Switch"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["switch case", "break keyword", "default keyword", "C switch 문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "switch"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_switch.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Switch]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`break` isn't optional cleanup — without it, C would keep executing every subsequent `case` block regardless of whether it matches, since `switch` on its own only decides WHERE to jump in, not where to stop; the source frames `break` as actively saving execution time by "ignoring" the rest of the switch block once a match is handled, implying that omitting it (fall-through) is a real and easy-to-make mistake in C, unlike languages where each case implicitly breaks. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`switch (expression)`** — evaluates the expression ONCE, then compares it against each `case` value to find a match. [S1]
|
||||
- **`case x:`** — a candidate value to match against; its code block runs if the switch expression equals `x`. [S1]
|
||||
- **`break`** — exits the switch block immediately once a matching case has been handled, preventing execution from continuing into subsequent cases. [S1]
|
||||
- **`default:`** — optional; runs if no case matches; must be the LAST statement in the switch and does not need its own `break`. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Weekday-name lookup via switch: `int day = 4; switch (day) { case 1: printf("Monday"); break; ... case 4: printf("Thursday"); break; ... }` — outputs "Thursday" for day 4. [S1]
|
||||
- Using default for unmatched cases: `int day = 4; switch (day) { case 6: printf("Today is Saturday"); break; case 7: printf("Today is Sunday"); break; default: printf("Looking forward to the Weekend"); }` — day 4 matches neither case 6 nor 7, so default runs. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **break 생략 시 다음 case로 계속 진행됨**: switch는 일치하는 case를 찾아 진입점만 결정할 뿐, break가 없으면 이후 모든 case의 코드가 계속 실행된다는 점(fall-through)이 암묵적으로 경고됨. [S1]
|
||||
- **default는 반드시 마지막에 위치**: default 키워드는 switch 블록의 마지막 statement여야 하며 break가 필요 없다는 점이 명시적으로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
요일 번호(1-7)를 요일 이름으로 변환하는 예제와, 주말이 아닌 요일에 대해 default로 "주말이 기대된다"는 메시지를 출력하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Using default to handle any value not matched by an explicit case (C):
|
||||
```c
|
||||
int day = 4;
|
||||
switch (day) {
|
||||
case 6:
|
||||
printf("Today is Saturday");
|
||||
break;
|
||||
case 7:
|
||||
printf("Today is Sunday");
|
||||
break;
|
||||
default:
|
||||
printf("Looking forward to the Weekend");
|
||||
}
|
||||
// Outputs "Looking forward to the Weekend"
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Conditions RealLife]], [[C While Loop]]
|
||||
- **참조 맥락:** switch 섹션 유일 챕터 — 반복문(Loops) 섹션의 while 루프(While Loop) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Switch — https://www.w3schools.com/c/c_switch.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Switch" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-syntax
|
||||
title: "C Syntax"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["main function", "include stdio", "C 문법"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "syntax"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_syntax.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Syntax]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The compiler is explicitly indifferent to whitespace and line breaks — the source shows the ENTIRE `main()` body collapsible onto a single line (`int main(){printf("Hello World!");return 0;}`) and produces identical behavior — meaning C's multi-line formatting convention exists purely for human readability, not because the language requires it, unlike languages where indentation/newlines are syntactically meaningful. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`#include <stdio.h>`** — includes a header enabling input/output functions like `printf()`; described as something that "almost always appears" in a C program. [S1]
|
||||
- **`main()`** — the special function where program execution begins; code inside its `{}` is what actually runs. [S1]
|
||||
- **Statement termination** — every C statement must end with a semicolon `;`. [S1]
|
||||
- **`return 0`** — ends `main()` and sends a value back to the operating system; `0` conventionally signals "everything worked." [S1]
|
||||
- **Whitespace insignificance** — blank lines and extra spaces are ignored by the compiler; used only to aid human readability. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Standard multi-line form: `#include <stdio.h> int main() { printf("Hello World!"); return 0; }`. [S1]
|
||||
- Equivalent single-line form (compiler behaves identically): `int main(){printf("Hello World!");return 0;}`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **줄바꿈/공백은 순전히 가독성 목적**: 컴파일러가 여러 줄로 쓰인 코드와 한 줄로 압축한 코드를 동일하게 처리한다는 점이 직접적인 코드 비교로 증명됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 이 챕터의 문장 단위 분해 설명이 이후 모든 C 코드를 읽는 기초 독해 능력의 토대가 된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
The canonical C program structure, annotated line by line:
|
||||
```c
|
||||
#include <stdio.h>
|
||||
|
||||
int main() {
|
||||
printf("Hello World!");
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Get Started]], [[C Statements]]
|
||||
- **참조 맥락:** C 프로그램 구조 설명 — 명령문(Statements) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Syntax — https://www.w3schools.com/c/c_syntax.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Syntax" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,73 @@
|
||||
---
|
||||
id: c-type-conversion
|
||||
title: "C Type Conversion"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["implicit conversion", "explicit conversion", "casting", "C 타입 변환"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "type-conversion", "casting"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_type_conversion.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Type Conversion]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Casting the RESULT of a division after the fact doesn't fix precision loss — `float sum = 5 / 2;` still prints `2.000000` because `5 / 2` is computed as INTEGER division BEFORE ever being assigned to `sum` — the cast must be applied to an OPERAND inside the division itself (`(float) 5 / 2`), proving that explicit conversion timing matters as much as the conversion existing at all. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Type conversion** — converting a value from one data type to another, either automatically (implicit) or manually (explicit). [S1]
|
||||
- **Implicit conversion** — done automatically by the compiler (e.g. assigning `int` to `float`); risky in the REVERSE direction, since assigning `float` to `int` silently TRUNCATES the decimal part with no warning. [S1]
|
||||
- **Explicit conversion (casting)** — manually placing a type in parentheses `(type)` before a value or variable to force conversion at a SPECIFIC point in an expression. [S1]
|
||||
- **Casting must happen INSIDE the expression, not after** — `float sum = 5 / 2;` still integer-divides first (yielding 2.000000); only `float sum = (float) 5 / 2;` produces the correct 2.5, because casting one operand to `float` before the division forces the WHOLE division to be floating-point. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Implicit int-to-float (safe direction): `float myFloat = 9; // 9.000000`. [S1]
|
||||
- Implicit float-to-int (risky, silently truncates): `int myInt = 9.99; // 9, the .99 is silently lost`. [S1]
|
||||
- The casting-timing trap: `float sum = 5 / 2; // still 2.000000 — integer division happens BEFORE assignment`. [S1]
|
||||
- The correct fix — casting an operand INSIDE the division: `float sum = (float) 5 / 2; // 2.500000`. [S1]
|
||||
- Cleaning up the display with decimal precision: `printf("%.1f", sum); // 2.5`. [S1]
|
||||
- Real-life percentage calculation combining casting with arithmetic: `int maxScore = 500; int userScore = 423; float percentage = (float) userScore / maxScore * 100.0; printf("User's percentage is %.2f", percentage);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **결과가 아닌 피연산자에 캐스팅해야 함**: float sum = 5 / 2;처럼 결과 변수만 float로 선언해서는 정수 나눗셈이 먼저 일어나 여전히 2.000000이 나오며, (float) 5 / 2처럼 나눗셈 안의 피연산자를 캐스팅해야만 올바른 2.5가 나온다는 점이 명확히 대비됨. [S1]
|
||||
- **암묵적 float→int 변환은 소수점을 조용히 버림**: 9.99를 int에 대입하면 경고 없이 9가 되어 .99가 사라진다는 점이 위험 요소로 명시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
게임 점수(423/500)를 백분율로 정확히 계산하기 위해 userScore를 float로 캐스팅한 뒤 나누는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Casting an operand inside the division to force floating-point arithmetic (C):
|
||||
```c
|
||||
int maxScore = 500;
|
||||
int userScore = 423;
|
||||
float percentage = (float) userScore / maxScore * 100.0;
|
||||
printf("User's percentage is %.2f", percentage); // 84.60
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Files Write]], [[C Data Types Dec]], [[C Macros]]
|
||||
- **참조 맥락:** 타입 변환 및 매크로 섹션 첫 챕터 — 전처리기와 매크로(Macros) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Type Conversion — https://www.w3schools.com/c/c_type_conversion.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Type Conversion" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
id: c-typedef
|
||||
title: "C typedef"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["type alias", "typedef struct", "C typedef"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "typedef"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_typedef.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C typedef]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`typedef` changes ZERO runtime behavior — the source explicitly states "your code will work the same without it" — meaning its entire value is communicative: `Temperature today = 25.5;` behaves byte-for-byte identically to `float today = 25.5;`, but tells a HUMAN reader what the number represents, which is exactly why it becomes essential once structs nest three levels deep (Owner inside Car inside Dealership) and repeatedly typing `struct` at every level would obscure the actual hierarchy being expressed. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`typedef existingType NewName;`** — creates an alias for an existing type; purely a naming convenience with no behavioral effect. [S1]
|
||||
- **Purely optional** — code behaves identically with or without it; the only benefit is readability/maintainability. [S1]
|
||||
- **`typedef struct {...} Name;`** — the common pattern that lets you write `Name variable;` instead of `struct Name variable;` everywhere afterward. [S1]
|
||||
- **Compounding benefit with nested structs** — as struct nesting grows deeper (Owner → Car → Dealership), typedef keeps each declaration and access chain readable by removing repeated `struct` keywords. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Simple type alias for clarity: `typedef float Temperature; Temperature today = 25.5; Temperature tomorrow = 18.6;` — `Temperature` communicates INTENT beyond just "this is a float." [S1]
|
||||
- typedef with struct, side by side: `struct Car { char brand[30]; int year; }; // needs "struct" everywhere` versus `typedef struct { char brand[30]; int year; } Car; // "Car car2 = ..." works directly`. [S1]
|
||||
- Three-level nested typedef'd structs kept readable: `typedef struct {...} Owner; typedef struct { ...; Owner owner; } Car; typedef struct { ...; Car featuredCar; } Dealership;` accessed via `d.featuredCar.owner.firstName`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **typedef는 선택 사항이며 동작에 영향 없음**: typedef 없이도 코드는 완전히 동일하게 동작하며, 유일한 이득은 가독성/유지보수성이라는 점이 원문에서 직접 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
Owner→Car→Dealership 3단계로 중첩된 구조체를 typedef로 깔끔하게 유지하는 예제가 원문에서 직접 실전 활용 사례로 제시됨(중첩이 깊어질수록 typedef의 이점이 커짐). [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
typedef keeping deeply nested struct declarations readable (C):
|
||||
```c
|
||||
typedef struct {
|
||||
char firstName[20];
|
||||
char lastName[20];
|
||||
} Owner;
|
||||
|
||||
typedef struct {
|
||||
char brand[20];
|
||||
int year;
|
||||
Owner owner;
|
||||
} Car;
|
||||
|
||||
typedef struct {
|
||||
char name[30];
|
||||
Car featuredCar;
|
||||
} Dealership;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Unions]], [[C Enums]], [[C Structs Nested]], [[C Memory Address]]
|
||||
- **참조 맥락:** 구조체·열거형·유니온 섹션 마지막 — 포인터 및 메모리(Pointers & Memory) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C typedef — https://www.w3schools.com/c/c_typedef.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C typedef" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,77 @@
|
||||
---
|
||||
id: c-unions
|
||||
title: "C Unions"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["union keyword", "shared memory members", "C 유니온"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "unions"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_unions.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Unions]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Writing to ANY member of a union silently invalidates every other member's previously-stored value — the source's example shows `u1.myNum = 1000;` followed by `u1.myLetter = 'A';` leaves `myNum` printing "no longer reliable" garbage, because unlike a struct where each member owns separate memory, a union's members OVERLAP the exact same bytes, so the last write always wins and there's no compiler warning when you accidentally read a stale member. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`union`** — syntactically similar to `struct` (same declaration/dot-access style), but semantically opposite: all members share ONE memory location instead of each having its own. [S1]
|
||||
- **Only one valid member at a time** — writing to any member overwrites the shared memory, silently invalidating whatever the previous member held. [S1]
|
||||
- **Size = largest member** — `sizeof(union)` equals the size of its biggest member, NOT the sum of all members (unlike a struct, whose size is roughly the sum of members plus padding). [S1]
|
||||
- **Use case** — when you only need to store ONE of several possible types at a time and memory savings matter; structs remain the default choice for storing/accessing multiple values simultaneously. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- The stale-value trap: `union myUnion { int myNum; char myLetter; char myString[30]; }; u1.myNum = 1000; u1.myLetter = 'A'; printf("myNum: %d\n", u1.myNum); // no longer reliable printf("myLetter: %c\n", u1.myLetter); // 'A'`. [S1]
|
||||
- Size determined by the largest member: `union myUnion { int myNum; char myString[36]; }; sizeof(u1); // 36 (the size of myString, the largest member)`. [S1]
|
||||
- Contrast with an equivalent struct's size: the same two members (`int` + `char[36]`) as a STRUCT would total ~40 bytes (4 + 36), versus the union's 36 bytes. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **유니온의 마지막 대입만 유효**: 서로 다른 멤버에 순서대로 값을 쓰면 이전에 쓴 멤버의 값은 조용히 무효화된다는 점이 명시적으로 경고됨 — 컴파일러가 이를 알려주지 않으므로 프로그래머가 직접 관리해야 함. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 여러 타입 중 한 번에 하나만 저장하면서 메모리를 절약해야 하는 상황(예: 프로토콜 파싱)이 유니온의 대표적 활용 사례로 원문에 조건으로만 언급됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Writing to one union member silently invalidates the previously-stored member (C):
|
||||
```c
|
||||
union myUnion {
|
||||
int myNum;
|
||||
char myLetter;
|
||||
char myString[30];
|
||||
};
|
||||
int main() {
|
||||
union myUnion u1;
|
||||
u1.myNum = 1000;
|
||||
u1.myLetter = 'A'; // myNum is now invalid — same memory was overwritten
|
||||
printf("myLetter: %c\n", u1.myLetter); // Prints 'A'
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Enums]], [[C Structs Padding]], [[C Typedef]]
|
||||
- **참조 맥락:** 유니온 — typedef 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Unions — https://www.w3schools.com/c/c_unions.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Unions" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-user-input
|
||||
title: "C User Input"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["scanf function", "fgets function", "C 사용자 입력"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.87
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "user-input", "scanf", "fgets"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_user_input.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C User Input]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`scanf("%s", ...)` treats WHITESPACE as a terminator — the source's own demonstration types "John Doe" but the program only prints "John," silently dropping everything after the first space — which is exactly why `fgets()` exists as a SEPARATE tool specifically for multi-word input, meaning the choice between `scanf()` and `fgets()` isn't stylistic, it's dictated by whether the expected input could ever contain a space. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`scanf(format, &variable)`** — reads user input matching the given format specifier; requires the `&` reference operator for basic types (but NOT for strings, since an array name is already a pointer). [S1]
|
||||
- **Multiple inputs in one call** — `scanf("%d %c", &myNum, &myChar);` reads several values matched to their respective format specifiers in order. [S1]
|
||||
- **String input via `scanf("%s", name)`** — no `&` needed (array name = pointer); requires a large-enough buffer declared in advance (e.g. `char firstName[30]`). [S1]
|
||||
- **`scanf`'s whitespace-termination limitation** — treats spaces/tabs as a terminating character, so it can only capture a SINGLE WORD even if the user types multiple words. [S1]
|
||||
- **`fgets(buffer, sizeof(buffer), stdin)`** — reads a full LINE of text including spaces, the correct tool for multi-word input like a full name. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic numeric input: `int myNum; scanf("%d", &myNum);`. [S1]
|
||||
- Multiple inputs in one call: `int myNum; char myChar; scanf("%d %c", &myNum, &myChar);`. [S1]
|
||||
- String input demonstrating the space-termination trap: `char fullName[30]; scanf("%s", &fullName); // "Type your full name: John Doe" → prints only "Hello John"`. [S1]
|
||||
- The `fgets()` fix for multi-word input: `char fullName[30]; fgets(fullName, sizeof(fullName), stdin); // "John Doe" → prints "Hello John Doe"`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **scanf("%s", ...)는 공백에서 끊김**: "John Doe"를 입력해도 공백을 종료 문자로 취급해 "John"만 출력된다는 점이 직접 예제로 증명되며, 여러 단어를 받으려면 fgets()를 써야 한다는 대안이 명확히 제시됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
사용자의 전체 이름(공백 포함)을 정확히 입력받기 위해 scanf() 대신 fgets()를 사용하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Reading a full line of text (including spaces) with fgets() instead of scanf() (C):
|
||||
```c
|
||||
char fullName[30];
|
||||
printf("Type your full name: \n");
|
||||
fgets(fullName, sizeof(fullName), stdin);
|
||||
printf("Hello %s", fullName); // "John Doe" prints in full
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.87
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Scope]], [[C Do While Loop]], [[C Date Time]]
|
||||
- **참조 맥락:** 사용자 입력 — 날짜와 시간(Date Time) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C User Input — https://www.w3schools.com/c/c_user_input.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C User Input" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-variables
|
||||
title: "C Variables"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["variable declaration", "int float char", "C 변수"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "variables"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Variables]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Directly `printf()`-ing a variable like `printf(myNum)` is explicitly called out as an ERROR — unlike Python, Java, or C++ where a print function can accept a variable directly, C requires a separate "format specifier" placeholder mechanism to print any value, meaning the most natural instinct coming from another language (just print the variable) is a compile-breaking mistake in C. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Variable** — a named container for storing a data value; must have a specific TYPE that dictates what kind of data it can hold. [S1]
|
||||
- **Three introductory types** — `int` (whole numbers), `float` (decimal numbers), `char` (a single character in single quotes). [S1]
|
||||
- **Declaration syntax** — `type variableName = value;`, or declare first and assign later (`int myNum; myNum = 15;`). [S1]
|
||||
- **No direct variable printing** — `printf(myNum)` is invalid; C requires format specifiers (covered in the next chapter) to print variable values. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Declare-and-assign in one line: `int myNum = 15;`. [S1]
|
||||
- Declare first, assign later: `int myNum; myNum = 15;`. [S1]
|
||||
- The explicit error case: `int myNum = 15; printf(myNum); // This will cause an error`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **다른 언어와의 출력 방식 차이**: Python/Java/C++와 달리 C에서는 printf()에 변수를 직접 넣어 출력할 수 없고 반드시 포맷 지정자를 사용해야 한다는 점이 명시적으로 경고됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 변수를 먼저 선언만 하고 나중에 값을 대입하는 패턴이 조건에 따라 값이 결정되는 실전 로직에서 흔히 쓰인다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Declaring a variable first, then assigning its value later (C):
|
||||
```c
|
||||
// Declare a variable
|
||||
int myNum;
|
||||
// Assign a value later
|
||||
myNum = 15;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Organize Code]], [[C Variables Names]], [[C Variables Format]]
|
||||
- **참조 맥락:** 변수 섹션 첫 챕터 — 변수 이름 규칙(Variables Names) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Variables — https://www.w3schools.com/c/c_variables.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Variables" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-variables-change
|
||||
title: "C Variable Values"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["reassignment", "self-referential assignment", "C 변수 값 변경"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "variables", "assignment"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables_change.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Variable Values]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
`x = x + 1` is explicitly explained not as a mathematical equation (which would be false — x can never equal x+1) but as an INSTRUCTION: "take the current value of x and add 1 to it, [then store the result back into x]" — a reframing crucial for anyone whose intuition for `=` comes from algebra rather than programming's assignment semantics. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Reassignment overwrites** — assigning a new value to an existing variable replaces the old value entirely; this is normal/expected behavior, not an error. [S1]
|
||||
- **Variable-to-variable copying** — `myNum = myOtherNum;` copies the CURRENT value of one variable into another; the two remain independent afterward (no live link). [S1]
|
||||
- **Copying into a previously-unassigned variable** — a variable declared without an initial value can still receive a value via copy-assignment later. [S1]
|
||||
- **Self-referential assignment (`x = x + 1`)** — reads the current value of `x`, computes `x + 1`, and stores the result back into `x`; this is an instruction/mutation, not an algebraic equality. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Simple reassignment: `int myNum = 15; myNum = 10; // Now myNum is 10`. [S1]
|
||||
- Variable-to-variable copy: `int myNum = 15; int myOtherNum = 23; myNum = myOtherNum; // myNum is now 23`. [S1]
|
||||
- Adding two variables into a third: `int x = 5; int y = 6; int sum = x + y;`. [S1]
|
||||
- Self-referential update: `int x = 5; x = x + 1; // x is now 6`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **= 기호는 수학적 등식이 아님**: x = x + 1이 대수적으로는 성립할 수 없는 식이지만, 프로그래밍에서는 "현재 x값에 1을 더해 다시 x에 저장하라"는 명령으로 해석되어야 한다는 점이 명시적으로 설명됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — x = x + 1 패턴이 이후 반복문(Loops) 챕터에서 카운터 증가 로직의 기초가 된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Self-referential assignment — reading and updating the same variable (C):
|
||||
```c
|
||||
int x = 5;
|
||||
x = x + 1; // x is now 6
|
||||
printf("%d", x);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables Names]], [[C Variables Multiple]], [[C While Loop]]
|
||||
- **참조 맥락:** 변수 값 변경과 재대입 — 여러 변수 한번에 선언하기(Variables Multiple) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Variable Values — https://www.w3schools.com/c/c_variables_change.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Variable Values" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-variables-format
|
||||
title: "C Format Specifiers"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["%d %f %c", "printf placeholders", "C 포맷 지정자"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "printf", "format-specifiers"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables_format.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Format Specifiers]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Format specifiers work identically whether the value comes from a VARIABLE or is a LITERAL typed directly (`printf("%d", 15)` behaves the same as `printf("%d", myNum)` when `myNum` is 15) — meaning the specifier's job is purely to describe the TYPE of whatever value follows in the argument list, not to reference a variable specifically, which is why C's earlier restriction against printing a bare variable (from the Variables chapter) is really a restriction about missing type information, not about variables per se. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Format specifier** — a `%`-prefixed placeholder inside a `printf()` string that tells C what type of value to expect and how to render it. [S1]
|
||||
- **Type-specific specifiers** — `%d` (integer), `%f` (floating point), `%c` (character); each must match the type of the value being printed. [S1]
|
||||
- **Text + variable combination** — mixing literal text and a specifier in one format string, separated by a comma for the argument: `printf("My favorite number is: %d", myNum);`. [S1]
|
||||
- **Multiple specifiers in one call** — `printf("My number is %d and my letter is %c", myNum, myLetter);` — arguments are matched to specifiers in left-to-right order. [S1]
|
||||
- **Specifiers work on literals too** — `printf("My favorite number is: %d", 15);` — the value need not be stored in a variable first. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic integer print: `int myNum = 15; printf("%d", myNum); // Outputs 15`. [S1]
|
||||
- Three types, three specifiers: `int myNum = 15; float myFloatNum = 5.99; char myLetter = 'D'; printf("%d\n", myNum); printf("%f\n", myFloatNum); printf("%c\n", myLetter);`. [S1]
|
||||
- Multiple specifiers in one printf: `printf("My number is %d and my letter is %c", myNum, myLetter);`. [S1]
|
||||
- Printing literals directly without variables: `printf("My favorite letter is: %c", 'D');`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **변수 없이도 리터럴에 포맷 지정자 적용 가능**: 값을 변수에 저장하지 않고도 리터럴을 직접 %d/%c 등으로 출력할 수 있다는 점이 확인되지만, 재사용/변경 가능성 때문에 변수 사용이 일반적으로 더 낫다고 언급됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 한 printf() 호출에 여러 타입(정수+문자)을 함께 출력하는 패턴이 이후 Real-Life 예제(학생 정보 출력)에서 그대로 확장 활용된다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Printing multiple different types in one printf() call using matching format specifiers (C):
|
||||
```c
|
||||
int myNum = 15;
|
||||
char myLetter = 'D';
|
||||
printf("My number is %d and my letter is %c", myNum, myLetter);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables]], [[C Variables Multiple]], [[C Variables RealLife]], [[C Data Types]]
|
||||
- **참조 맥락:** 포맷 지정자 — 실전 변수 활용 예제(Variables RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Format Specifiers — https://www.w3schools.com/c/c_variables_format.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Format Specifiers" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
id: c-variables-multiple
|
||||
title: "C Declare Multiple Variables"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["chained assignment", "comma-separated declaration", "C 여러 변수 선언"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "variables"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables_multiple.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Declare Multiple Variables]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Both shortcuts covered here — comma-separated declaration (`int x = 5, y = 6, z = 50;`) and chained assignment (`x = y = z = 50;`) — REQUIRE all variables to share the exact same type, meaning these conveniences only apply within a single type declaration and cannot be used to initialize variables of different types in one statement. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Comma-separated declaration** — `type a = v1, b = v2, c = v3;` declares and initializes multiple same-type variables in one statement. [S1]
|
||||
- **Same-type restriction** — all variables in one comma-separated declaration must be of the SAME type; mixing types in one statement is not allowed. [S1]
|
||||
- **Chained assignment** — `x = y = z = 50;` assigns the same value to multiple already-declared variables at once. [S1]
|
||||
- **Readability tradeoff** — the source explicitly notes that declaring on one line is convenient, but separate lines are often easier to read. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Comma-separated declaration with individual values: `int x = 5, y = 6, z = 50; printf("%d", x + y + z);`. [S1]
|
||||
- Chained assignment of one shared value: `int x, y, z; x = y = z = 50; printf("%d", x + y + z);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 여러 카운터 변수를 0으로 동시에 초기화하는 상황(x = y = z = 0)이 체이닝 대입의 대표 실전 활용이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Chained assignment giving multiple variables the same value at once (C):
|
||||
```c
|
||||
int x, y, z;
|
||||
x = y = z = 50;
|
||||
printf("%d", x + y + z);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables Change]], [[C Variables Format]]
|
||||
- **참조 맥락:** 여러 변수 동시 선언 — 포맷 지정자(Variables Format) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Declare Multiple Variables — https://www.w3schools.com/c/c_variables_multiple.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Declare Multiple Variables" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
id: c-variables-names
|
||||
title: "C Variable Names (Identifiers)"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["identifiers", "camelCase", "C 변수 이름 규칙"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.85
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "variables", "naming"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables_names.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Variable Names (Identifiers)]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
Variable names in C are strictly CASE-SENSITIVE at the identifier level — `myVar` and `myvar` are two completely distinct variables, not a warning or a style issue — meaning a single accidental capitalization typo silently creates a second, separate variable rather than referencing the intended one, a class of bug the compiler won't catch as a naming error. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Identifier** — the unique name given to a variable. [S1]
|
||||
- **Naming rules** — letters, digits, and underscores allowed; must begin with a letter or underscore; case-sensitive; no whitespace or special characters (`!`, `#`, `%`, etc.); reserved words (e.g. `int`) cannot be used as names. [S1]
|
||||
- **Descriptive naming recommended** — `minutesPerHour` over `m`, for maintainability, even though both compile correctly. [S1]
|
||||
- **Two common naming styles** — camelCase (`totalScore`) or underscore-separated (`total_score`); the source recommends picking one and staying consistent. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Valid names: `age`, `_count`, `totalSum`. [S1]
|
||||
- Invalid names and why: `1age` (starts with a digit), `my-age` (contains a hyphen), `int` (reserved word). [S1]
|
||||
- Descriptive vs terse naming contrast: `int minutesPerHour = 60;` (clear) versus `int m = 60;` (compiles, but unclear intent). [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **대소문자 구분의 함정**: myVar와 myvar가 서로 다른 변수로 취급된다는 점이 명시되며, 이는 오타로 인한 미묘한 버그의 원인이 될 수 있다는 점을 시사함. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — camelCase나 언더스코어 스타일 중 하나를 프로젝트 전체에 일관되게 적용하는 것이 실전 코드 컨벤션의 기본이다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Descriptive vs. terse variable naming (C):
|
||||
```c
|
||||
// Good variable name
|
||||
int minutesPerHour = 60;
|
||||
// OK, but not so easy to understand what m actually is
|
||||
int m = 60;
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.85
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables]], [[C Variables Change]]
|
||||
- **참조 맥락:** 변수 이름 규칙 — 변수 값 변경(Variables Change) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Variable Names (Identifiers) — https://www.w3schools.com/c/c_variables_names.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Variable Names (Identifiers)" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
id: c-variables-reallife
|
||||
title: "C Variables - Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["real-life variables", "rectangle area example", "C 변수 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.83
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "variables", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_variables_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C Variables - Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The source explicitly admits its own teaching convention (naming variables `myInt`/`myNum`/`myChar` after their TYPE) is an artificial simplification "to avoid confusion" — and this real-life chapter exists specifically to break that habit, showing that real variables should be named after what they REPRESENT (`studentID`, `studentGrade`) not what type they are, reinforcing the earlier Variable Names chapter's descriptive-naming advice with a concrete before/after contrast. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Type-based teaching names vs. domain names** — tutorial examples use `myNum`/`myChar` for clarity during learning, but real programs should name variables after their real-world meaning. [S1]
|
||||
- **Multiple variables of different types working together** — one program can combine `int`, `float`, and `char` variables all representing facets of the same real-world entity (a student record). [S1]
|
||||
- **Calculate-then-print pattern** — perform a calculation first, store the result in a variable, and only then print it — rather than computing inline inside the print call. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Student record combining three types: `int studentID = 15; int studentAge = 23; float studentFee = 75.25; char studentGrade = 'B';` printed with matching `%d`/`%f`/`%c` specifiers. [S1]
|
||||
- Rectangle area calculate-then-print: `int length = 4; int width = 6; int area; area = length * width; printf("Area of the rectangle is: %d", area);`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- 현재까지 발견된 모순 사항 없음 (No contradictions found in available sources).
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
현재 발견된 실제 적용 사례가 없습니다 — 학생 정보(ID/나이/수수료/학점)를 하나의 프로그램에서 함께 다루는 예제가 서로 다른 타입의 변수를 실제 데이터 모델링에 사용하는 대표 사례다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Calculating a value first, then printing the stored result (C):
|
||||
```c
|
||||
int length = 4;
|
||||
int width = 6;
|
||||
int area;
|
||||
area = length * width;
|
||||
printf("Area of the rectangle is: %d", area);
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.83
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Variables Format]], [[C Variables Names]], [[C Data Types]]
|
||||
- **참조 맥락:** 변수 섹션 마지막 — 데이터 타입(Data Types) 섹션으로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C Variables - Examples — https://www.w3schools.com/c/c_variables_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C Variables - Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
id: c-while-loop
|
||||
title: "C While Loop"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["while statement", "zero-iteration loop", "C while 반복문"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.86
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "while"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_while_loop.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C While Loop]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
A `while` loop can run ZERO times — if its condition is already false the very first time it's checked (e.g. `int i = 10; while (i < 5) {...}`), the body never executes at all, not even once — a behavior the source explicitly contrasts against the upcoming do/while chapter, which guarantees at least one execution regardless of the initial condition. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **`while (condition) { ... }`** — repeats the block as long as the condition remains true, checked BEFORE each iteration (including the first). [S1]
|
||||
- **Zero-iteration possibility** — if the condition is false from the start, the loop body never runs at all. [S1]
|
||||
- **Mandatory condition-variable update** — forgetting to change the loop-controlling variable inside the body (e.g. omitting `i++`) causes an infinite loop. [S1]
|
||||
- **`i` as a counter convention** — the source explains `i` is traditionally used because it's short and stands for "index"/"iterator," not an arbitrary choice. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Basic counting loop: `int i = 0; while (i < 5) { printf("%d\n", i); i++; }`. [S1]
|
||||
- Countdown loop: `int countdown = 3; while (countdown > 0) { printf("%d\n", countdown); countdown--; } printf("Happy New Year!!\n");`. [S1]
|
||||
- Zero-iteration case: `int i = 10; while (i < 5) { printf("This will never be printed\n"); i++; }` — body never executes since the condition is false immediately. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **조건이 처음부터 거짓이면 while 루프는 한 번도 실행 안 됨**: do/while 루프(다음 챕터)와 달리 일반 while 루프는 시작부터 조건이 거짓이면 본문이 단 한 번도 실행되지 않는다는 점이 명시적으로 대비됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
카운트다운 후 "Happy New Year!!"를 출력하는 예제가 원문에서 직접 실전 활용 사례로 제시됨. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
A while loop that never executes because its condition is false from the start (C):
|
||||
```c
|
||||
int i = 10;
|
||||
while (i < 5) {
|
||||
printf("This will never be printed\n");
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.86
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C Switch]], [[C While Loop RealLife]], [[C Do While Loop]]
|
||||
- **참조 맥락:** 반복문 섹션 첫 챕터 — while 루프 실전 예제(While Loop RealLife) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C While Loop — https://www.w3schools.com/c/c_while_loop.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C While Loop" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
id: c-while-loop-reallife
|
||||
title: "C While Loop Examples"
|
||||
category: "Programming_Language"
|
||||
status: "draft"
|
||||
verification_status: "conceptual"
|
||||
canonical_id: ""
|
||||
aliases: ["number reversal", "Yatzy example", "C while 루프 실전 예제"]
|
||||
duplicate_of: ""
|
||||
source_trust_level: "B"
|
||||
confidence_score: 0.84
|
||||
created_at: 2026-07-04
|
||||
updated_at: 2026-07-04
|
||||
review_reason: ""
|
||||
merge_history: []
|
||||
tags: ["c", "programming-language", "w3schools", "loops", "while", "real-life-example"]
|
||||
raw_sources: ["https://www.w3schools.com/c/c_while_loop_reallife.php"]
|
||||
applied_in: []
|
||||
github_commit: ""
|
||||
---
|
||||
|
||||
# [[C While Loop Examples]]
|
||||
|
||||
## 🎯 한 줄 통찰 (One-line insight)
|
||||
The number-reversal example uses `while (numbers)` — a bare integer as the condition, not an explicit comparison — relying on C's implicit rule that any NON-ZERO value is truthy and `0` is falsy; the loop naturally terminates once repeated division (`numbers /= 10`) drives the value down to exactly 0, showing that C loop conditions don't need to be boolean-shaped expressions at all, just any value that eventually becomes 0. [S1]
|
||||
|
||||
## 🧠 핵심 개념 (Core concepts)
|
||||
- **Bare-integer condition** — `while (numbers)` treats any non-zero `numbers` as true; the loop stops precisely when `numbers` becomes 0. [S1]
|
||||
- **Digit extraction via `% 10` and `/ 10`** — `numbers % 10` isolates the last digit; `numbers /= 10` removes it, a combination reused from the modulus/division operators. [S1]
|
||||
- **Number reversal by rebuilding** — `revNumbers = revNumbers * 10 + numbers % 10;` shifts previously-extracted digits left and appends the newly extracted one, building the reversed number digit by digit. [S1]
|
||||
- **While loop combined with if/else** — the Yatzy example nests conditional logic inside the loop body to react differently depending on the current iteration's value. [S1]
|
||||
|
||||
## 📖 세부 내용 (Details)
|
||||
- Even-numbers-only printer: `int i = 0; while (i <= 10) { printf("%d\n", i); i += 2; }`. [S1]
|
||||
- Number reversal using a bare-integer condition: `int numbers = 12345; int revNumbers = 0; while (numbers) { revNumbers = revNumbers * 10 + numbers % 10; numbers /= 10; }`. [S1]
|
||||
- Yatzy dice-checking loop: `int dice = 1; while (dice <= 6) { if (dice < 6) { printf("No Yatzy\n"); } else { printf("Yatzy!\n"); } dice = dice + 1; }`. [S1]
|
||||
|
||||
## ⚖️ 모순 및 업데이트 (Contradictions & updates)
|
||||
- **정수 자체가 조건이 될 수 있음**: while(numbers)처럼 비교 연산자 없이 정수 자체를 조건으로 사용할 수 있고, 0이 아니면 참, 0이면 거짓으로 취급된다는 점이 예제로 확인됨. [S1]
|
||||
|
||||
## 🛠️ 적용 사례 (Applied in summary)
|
||||
12345를 54321로 뒤집는 숫자 반전 알고리즘이 원문에서 직접 실전 활용 사례로 제시되며, 나머지(%)와 몫(/) 연산을 조합해 자릿수를 하나씩 분해/재조립하는 기법을 보여준다. [S1]
|
||||
|
||||
## 💻 코드 패턴 (Code patterns)
|
||||
Reversing a number's digits using a bare-integer while condition (C):
|
||||
```c
|
||||
int numbers = 12345;
|
||||
int revNumbers = 0;
|
||||
while (numbers) {
|
||||
revNumbers = revNumbers * 10 + numbers % 10;
|
||||
numbers /= 10;
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 검증 상태 및 신뢰도
|
||||
- **상태:** draft
|
||||
- **검증 단계:** conceptual
|
||||
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
|
||||
- **신뢰 점수:** 0.84
|
||||
- **중복 검사 결과:** 신규 생성 (New discovery)
|
||||
|
||||
## 🔗 지식 그래프 (Knowledge Graph)
|
||||
- **상위/루트:** [[C Tutorial]]
|
||||
- **관련 개념:** [[C While Loop]], [[C Do While Loop]], [[C Operators Arithmetic]]
|
||||
- **참조 맥락:** while 루프 실전 예제 — do/while 루프(Do While Loop) 챕터로 이어짐.
|
||||
|
||||
## 📚 출처 (Sources)
|
||||
- [S1] W3Schools — C While Loop Examples — https://www.w3schools.com/c/c_while_loop_reallife.php
|
||||
|
||||
## 📝 변경 이력 (Change history)
|
||||
- 2026-07-04: Initial draft synthesized from the W3Schools "C While Loop Examples" page (Astra wiki-curation, P-Reinforce v3.1 format).
|
||||
Reference in New Issue
Block a user