함수 및 제어 구조
함수를 정의하고 가시성 지정자(public, private, internal, external)를 사용하며 제어 흐름(if/else, 반복문)을 구현하는 방법을 배웁니다.
함수 및 제어 구조은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 3개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Functions in Solidity?
Functions are named blocks of code that perform specific tasks within your smart contract. They are fundamental for organizing your contract's logic, making it reusable, and improving readability.
Think of functions as the actions or operations your smart contract can perform, like calculating a value or updating a state variable.
Defining Your First Function
A basic function includes the function keyword, a name, optional parameters, a visibility specifier, and an optional return type. Here's a simple function that returns a greeting:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyFirstFunctions {
function greet() public pure returns (string memory) {
return "Hello, CoddyKit!";
}
}Functions with Parameters & Returns
Functions can accept inputs (called parameters) and produce outputs (return values). This allows them to perform dynamic operations based on the data you provide.
For example, a function can take two numbers and return their sum.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MathFunctions {
function add(uint a, uint b) public pure returns (uint) {
return a + b;
}
function subtract(uint a, uint b) public pure returns (uint) {
// Ensure positive result for unsigned integers
if (a >= b) {
return a - b;
} else {
return 0;
}
}
}Understanding Function Visibility
Function visibility specifies who can call a function and how. This is crucial for security and controlling access to your contract's logic and data. There are four main types:
public: Callable from anywhere (externally or internally).private: Only callable from within the current contract.internal: Callable from within the contract and derived contracts.external: Only callable from outside the contract.
Public and Private Functions
public functions are the most common, allowing DApps and other contracts to interact with your contract. private functions are for internal logic that should not be exposed or called directly from outside.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VisibilityDemo1 {
uint private _secretNumber = 42;
// Public function, callable by anyone
function getSecretNumber() public view returns (uint) {
// Can call private functions internally
return _getSecret();
}
// Private function, only callable from within this contract
function _getSecret() private view returns (uint) {
return _secretNumber;
}
}Internal and External Functions
internal functions are similar to private but can also be called by contracts that inherit from the current contract. external functions can ONLY be called from outside the contract (e.g., by a user or another contract), making them gas-efficient for external-only interactions.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VisibilityDemo2 {
uint public counter = 0;
// External function, only callable from outside
function incrementExternal() external {
// Can call internal functions
_incrementInternal();
}
// Internal function, callable from within this contract
// and derived contracts
function _incrementInternal() internal {
counter++;
}
// Note: Calling an external function internally
// (e.g., this.incrementExternal()) is not allowed
// and would result in a compile error.
}Conditional Logic: If/Else
Control flow statements allow your contract to execute different code paths based on conditions. The if/else statement is fundamental for making decisions in your contract's logic.
if (condition): Executes a block of code if the condition is true.else if (anotherCondition): Checks another condition if the firstifwas false.else: Executes code if all precedingifandelse ifconditions were false.
If/Else Example
This example demonstrates how to use if, else if, and else to categorize a number. This is a common pattern for handling different scenarios.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract ConditionalChecks {
function checkNumber(uint num) public pure returns (string memory) {
if (num > 100) {
return "Number is large.";
} else if (num > 50) {
return "Number is medium.";
} else {
return "Number is small.";
}
}
}Looping with `for`
Loops allow you to execute a block of code multiple times. In Solidity, the for loop is used for iterating a known number of times.
Important: Be extremely cautious with loops that involve many iterations in Solidity, as each operation costs gas. Complex or unbounded loops can lead to very high transaction fees or even run out of gas, making your transaction fail!
For Loop Example
Here's a basic for loop that sums numbers up to a given limit. For practical contracts, ensure the limit is always small and fixed, or avoid loops where gas costs could become prohibitive.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract LoopDemo {
function sumUpTo(uint limit) public pure returns (uint) {
// In real contracts, 'limit' should be very small
// to avoid excessive gas costs.
uint total = 0;
for (uint i = 0; i < limit; i++) {
total += i;
}
return total;
}
}Test Your Knowledge!
Which of the following statements about Solidity function visibility modifiers are TRUE?
Functions & Control Flow Summary
Great job! In this lesson, you gained essential knowledge about:
- Defining functions to organize and modularize your contract's logic.
- Understanding and applying
public,private,internal, andexternalvisibility modifiers to control function access. - Implementing conditional logic using
if/elsestatements for decision-making. - Understanding the basics of
forloops and the critical importance of gas considerations when using them.
These building blocks are fundamental for creating dynamic, secure, and efficient smart contracts. Next, we'll explore the Remix IDE to compile and deploy your contracts!
자주 묻는 질문
“함수 및 제어 구조” 강의는 무료인가요?
네 — “함수 및 제어 구조” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 3개의 강의가 포함되어 있습니다.
“함수 및 제어 구조”에서 뭘 배우나요?
함수를 정의하고 가시성 지정자(public, private, internal, external)를 사용하며 제어 흐름(if/else, 반복문)을 구현하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 3번째 강의입니다.
“함수 및 제어 구조” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Solidity 입문
- 변수 및 데이터 형식
- 함수 및 제어 구조