공부 좀 하자/Unity C# 기초

7.연산자(증감)

개발성문 2022. 8. 3. 12:24

증감 연산자는 피연산자(Operand)의 전후로 사용하며 기호는 ++, -- 입니다.

이때, 증감 값은 1로 고정되어 있습니다.

 

피연산자(Operand) 의 전위에 사용하는 것을 전위형, 피연산자Operand)의 후위에 사용하는 것은 후위형 이라고 합니다.

 

전위형은 계산을 우선적으로 처리합니다.

 

후위형은 계산이 나중에 처리됩니다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassDefault  : MonoBehaviour
{
    int op1 = 38;

    // Start is called before the first frame update
    void Start()
    {
       print("전위형 : " + ++op1);
       print("후위형 : " + op1++);
       print("최종 : " + op1);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

전위형을 계산을 먼저 처리 하기 때문에 39가 출력이 되었고,

후위형은 39에서 계산은 나중에 처리되기 때문에 39가 먼저 출력된 후에 1이 증가합니다.

그래서 최종 변수를 출력해보면 그때 40값이 출력되게 되는 것입니다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassDefault  : MonoBehaviour
{
    int op1 = 51;

    // Start is called before the first frame update
    void Start()
    {
       op1++;
       print(op1);
       ++op1;
       print(op1);
       print(op1++);
       print(++op1);
       ++op1;
       op1++;
       print(op1++);
       print(op1);
       print(++op1);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

결과를 미리 예측해보고 답과 비교해보세요.