1.4.7 const 활용

포인터를 const로 정의하면, 그 포인터가 가리키는 값을 변경할 수 없다.

int test(void)
{
    char s[] = "test";
    const char * p = s;
    p[0] = 'T';    /* const 포인터가 가리키는 주소의 값을 변경하려고 시도    */

    return 0;
}
1.4.8 const를 인자로 활용
void strcopy(char * dst, const char * src)
{
    while (*src != '\0')
        *(dst++) = *(src++);
    *dst = '\0';
}
  • const char *로 정의한 포인터가 가리키는 값은 변경할 수 없다. (경고)
  • const char * 포인터를 char *로 형변환 하는 것은 허용되지 않는다. (경고)

const를 반환하는 함수의 활용 예

typedef enum { Black, White, Blue, Red, Green } Color;

const char * ColorName(Color c)
{
    const char * s;
    switch(c)
    {
        case Black: s = "Black" break;
        case White: s = "White" break;
        case Blue : s = "Blue"  break;
        case Red  : s = "Red"   break;
        case Green: s = "Green" break;
        default   : s = "Unknown";
    }

    return s;
}
1.4.9 const를 사용할 때 주의사항

const로 선언할 수 있는 것은 모두 const로 선언하는 것이 좋을 것처럼 여겨진다. 하지만 실제로는 그렇지 않다. 특히 함수가 깊게 중첩되는 경우에는 const를 사용하지 않는 것이 좋다.

'C' 카테고리의 다른 글

Unity를 이용한 TDD - 2  (0) 2014.04.13
volatile  (0) 2014.04.09
Unity를 이용한 TDD  (0) 2014.04.02
[도서] 쉽게 배우는 C프로그래밍 테크닉 - 2.2 헤더 파일 만들기  (0) 2014.03.04
gdb 사용법  (0) 2014.03.03

GDB 사용법

다음 예제는 introduction to GDB a tutorial - Harvard CS50 (http://www.youtube.com/watch?v=sCtY--xRUyI)에서 가져왔다. 프로그램은 factorial을 구하는 것으로 버그를 가지고 있어서 제대로 동작하지 않는다.

/* filename : factorial.c */
#include <stdio.h>

int main(void)
{
        int num;
        int factorial;
        int i;

        do
        {
                printf("Enter a positive integer: ");
                scanf("%d",&num);
        }
        while(num<0);

        for(i=0; i<=num;i++)
                factorial = factorial * i;

        printf("%d! = %d\n", num, factorial);

        return 0;
}
Compile하는 법

Compile option으로 -g을 넣는다.

gcc -g factorial.c`)
gdb 실행법
gdb ./factorial
gdb 종료법
quit
break point 걸기
break main
line별로 실행하기
next # go to next line
run
기타
list

Koan - Methods

Case 115

첫번째 테스트는 메소드의 리턴값의 class이다.

  def test_calling_with_variable_arguments
    assert_equal __, method_with_var_args.class
    assert_equal __, method_with_var_args
    assert_equal __, method_with_var_args(:one)
    assert_equal __, method_with_var_args(:one, :two)
  end

'Ruby' 카테고리의 다른 글

YAML 사용하기  (0) 2014.03.07
Koan - Regular Expressions  (0) 2014.02.28
Koans - Symbols  (0) 2014.02.27
Ruby에서의 TDD  (0) 2014.02.22
Windows 환경에서 Shotgun이 실행되지 않을때  (0) 2014.02.21

+ Recent posts