[C#] 예약어(checked , unchecked), params

[C#] 예약어(checked , unchecked), params

- checked : 오버플로, 언더플로가 자동으로 되는 것을 방지하고 오류를 출력

- unchecked : 오버플로, 언더플로가 일어나도 오류를 출력하지 않는다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp__Checked
{
    class Program
    {
        static void Main(string[] args)
        {
            short c1 = 32767;
            c1++;
            Console.WriteLine(c1); // 출력결과 -32768 : 오버플로

            int n1 = 32768;
            c1 = (short)n1;
            Console.WriteLine(c1); // 출력결과 -32768 : 오버플로

            short c2 = -32768;
            c2--;
            Console.WriteLine(c2); //출력결과 32767 : 언더플로

            short c = 32767;
            int n = 32768;
            //오버플로, 언더플로가 자동으로 되는 것을 방지하고 오류를 출력 checked
            checked
            {
                c++;
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp__Checked
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Add(1, 2, 3));
            PrintAll("Result", 2, 1.3);
        }

        //가변 매개변수 : params 
        static int Add(params int[] values)
        {
            int total = 0;
            for(int i =0; i < values.Length; i++)
            {
                total += values[i];
            }
            return total;
        }

        //값형식이 다른경우 object로 받는다.
        static void PrintAll(params object[] values)
        {
            foreach(object value in values)
            {
                Console.WriteLine(value);
            }
        }

    }
}

댓글

이 블로그의 인기 게시물

[파이썬] #2-모듈설치 및 스파이더(spyder)사용

[Tool-Tip] 에디트플러스에서 자동정렬기능 추가하기

[파이썬] #1- 아나콘다 설치, 아나콘다 파이썬 환경 만들기