본문 바로가기

C# 문법 기초 - C++과 다른 점

@코야딩구2025. 6. 9. 22:00

이미 C++을 배웠기 때문에 오늘 배운 C# 문법 기초 중 C++과 다른 점만 모아봤다.

다른 점은 다음과 같다. 

1. 전처리 지시문

2. 문자 출력, 입력

3. 형변환

4. 배열 초기화

5. 범위 기반 for문(foreach문)

6. 클래스, 함수 정의 순서와 클래스 초기화

7. 최상위 문

// C# 문법 기초 중 C++과 다른 점 1

// 1. C++의 전처리 지시문 #include <> 가 없다.

// 2. 출력: C에는 printf(), C++에는 cout이 있었다면 C#에는 Console.WriteLine();이 있다. 
//    입력: C의 scanf, C++의 cin, C#의 Console.ReadLine();
string coding_club = "코코딩딩1";
int year = 2025;                       // 출력:
Console.WriteLine(coding_club);        // 코코딩딩1                                
Console.WriteLine("코코딩딩2");        // 코코딩딩2                           
Console.WriteLine(year);               // 2025                           
Console.WriteLine(2025 * 10000 + 609); // 20250609                           
// 증감 연산자도 똑같이 적용된다.                                   
int num1 = 2;                                                       
int num2 = 2;              // 출력:                                
Console.WriteLine(--num1); // 1                                    
Console.WriteLine(num1);   // 1                                    
Console.WriteLine(num2++); // 2                                    
Console.WriteLine(num2);   // 3                                    
                                                                   
//3. C++에서는 못보고 언리얼에서만 봤던 형변환 방식이 있다.        
// 기존 방식 = 단순 형변환, ex. (int)4.11                          
coding_club = Convert.ToString(year); // 출력:                 
Console.WriteLine(coding_club);       // 2025
// C# == 언리얼에서 본 방식                                        
string iStr1 = "100";                                              
string iStr2 = "1zz";
int x1 = 119;
int x2 = 112;
// int.TryParse(iStr1, out x1)의 반환값으로 형변환 성공 여부를 반환한다.
Console.WriteLine(int.TryParse(iStr1, out x1)); // True
Console.WriteLine(x1);                          // 100
Console.WriteLine(int.TryParse(iStr2, out x2)); // False
Console.WriteLine(x2);                          // 0, ***0으로 초기화됨

// 4. 배열 초기화
// C++: 데어티 타입 변수명[] -> string game[3], string game[3] = {"메이", "플", "스토리"};
// C#: 데이터 타입[] 변수명 -> 
string[] game1 = new string[3]; // 선언과 동시에 할당 = 초기화
string[] game2;// 선언만 하고
game2 = new string[3]; // 추후 할당
string[] game3 = new string[3] { "League of Legends", "메이플 스토리", "디아블로" }; // 크기에 따라 
string[] game4 = new string[] { "League of Legends", "메이플 스토리" }; // 크기 지정 안해도 가능
string[] game5 = { "League of Legends", "메이플 스토리", "디아블로" }; // new string[] 생략가능 = rvalue C++과 비슷
// 5. 범위 기반 for문 == foreach문
// C++: for(string game : games)
// C#: foreach(변수타입 반복변수 in 배열)
string[] games = new string[3] { "League of Legends", "메이플 스토리", "디아블로" };
foreach (string game in games)
{
    Console.WriteLine(game);
}
// 출력:
// League of Legends
// 메이플 스토리
// 디아블로
// 제 이름은 chad, 직업은 전사, 레벨은 입니다

// 6. 선언 순서에 영향을 받지 않음
// 클래스가 더 아래에 정의되어있지만 초기화 가능
// ********new Character();의 반환값이 포인터가 아니라 래퍼런스******
Character myCharacter = new Character();
myCharacter.userName = "chad";
myCharacter.job = "전사";
myCharacter.level = "20";
myCharacter.IntroduceCharacter(); // 제 이름은 chad, 직업은 전사, 레벨은 입니다.
// 변수가 할당되지 않으면 사용불가 = 오류
// Character myCharacter2;
//myCharacter2.job = "무직";

// 함수도 아래에 정의되어있지만 호출 가능
WhyNotError(); // 그것이 C#이다.



void WhyNotError()
{
    Console.WriteLine("그것이 C#이다.");
}
// 7. **현재 Main 없이 파일 최상단에 코드를 바로 작성할 수 있는 최상위 문을 기반으로 작성했기 때문에,
// class 밑에 함수 정의, 변수 선언 등 class 정의 제외 아무것도 안됨
class Character
{
    public string userName = "";
    public string job = "";
    public string level = "";

    public void IntroduceCharacter()
    {
        Console.WriteLine("제 이름은 " + userName + ", 직업은 " + job + ", 레벨은 " + "입니다.");
    }
}

'Programming > C#' 카테고리의 다른 글

C# 박싱과 언박싱  (0) 2025.07.07
C# 문자열  (0) 2025.06.17
C# is와 as (Type Checking and Casting)  (0) 2025.06.11
C# ref vs out (Pass by Reference)  (0) 2025.06.11
C# Convert, Parse와 TryParse  (0) 2025.06.10
목차