3.16(금) 우선순위에 대해서..

from Study/C언어 2007/03/16 10:27 view 30266
 

연산자

종류
결합성
우선순위
()  []  .  ->
최우선연산자
좌->우
높다
!  ~  -  *  &  sizeof  ++  -- cast
단항연산자
우->좌

* /  %  +  -
<<  >>
<  <=  >  >=  !=  ==
&&  ||  &  |  ^
이항연산자
좌->우

?:
삼항연산자
우->좌

=  +=  -=  *=  /=  %=  <<=  >>=  &=  |=  ^=
대입연산자
우->좌

,
순차연산자
좌->우
낮다

x = x + 1; x += 1; 의 줄여 쓰는게 가능하다. 하지만 =+ 는 되지 않는다.

이는 이항연산자가 대입연산자보다 우선순위가 빠르기 때문이다. 우선순위에 따라

좌->우로 컴파일하는데 +=를 만나면 x  와 1을 + 하는 이항연산을 하고 이값을 = 에

따라 lvalue에 대입시킨다.


int i = 5;
j = ++i + ++i;
// j 는 14가 된다.
i=5;
j = i++ + i++;
 // j는 10이 된다.

 ++i + ++i 는 언뜻보면 결과가 13 일 것 같다. 하지만 VC++ 컴파일러는 ++i 연산을 하게되면

스택내에 저장 되어 있는 값을 변경해준다. 그래서 6 + 7 일것 같지만 + 연산을 하면

변수 i에 저장된 값으로 이항연산을 하게 된다. 그래서 7 + 7 의 연산을 하는 애매모호한

값이 나오게 된다.

 i++ + i++ 는 5 + 6 으로 착각하기 쉽다. 하지만 후위증가는 문장의 끝인 ;(세미콜론)이

나와야 증가를 수행하게 된다. 즉 5 + 5로 연산을 수행 하고 문장이 끝나야 증가해서

i는 7이 된다.


int i = 5
printf("%d , %d", i , ++i);
//출력 6,6

 C는 함수의 인수를 뒤에서부터 순서대로 전달하도록 함수호출규약으로 정해 놓았다.


 if(y + 4 == 4 || ++y * 4 == 0)
 {
  printf("%d\n", y);
  printf("!\n");
 }

 그냥 혹시나 해서 이상한 코드를 만들어 보았다. if 문의 조건을 살펴볼때 + || * 이나

* || ( + ) 형식의 조건이 들어 있다면 왼쪽 먼저 일까 오른쪽이 먼저 일까 생각해 봤는데


이항연산자를 만나면 다른 이항연산자가 없다면 우선순위 비교 자체를 하지 않을 것이므

로....하여간 좀 바보같다..ㅠ_ㅠ

추가 : *&a[3] 을 우선순위대로 풀어보면 a 의 3번째 주소값의 indirection 을 행한다.

여기엔 * & [] 세가지의 연산자가 있는데 [] > & == * 이지만 & 와 *가 우선순위가 같다면 결합성이 우->좌

이기 때문에 & 먼저 연산되는 것을 알고 있자.
 

(Quiz)어떤 회사의 입사문제.

from Study/Quiz 2007/03/16 08:57 view 130019

출처 : http://blog.naver.com/comsik76/30005559569

컴파일시 에러 날(?) 곳을 찾아보아요.(문법적 오류 or 논리적 오류)

// composite.h

#include <list>
#include <memory>

// Composite 패턴을 구현하도록 하는 클래스
template <typename Type, typename Pointer>
class  xListComposite : public std::list<Pointer>
{
public :
 // 생성자
 xListComposite();
 // 소멸자
 ~xListComposite();

 // 부모 composite를 설정한다.
 inline void       setParent(const xListComposite* parent);
 // 부모 composite를 반환한다.
 inline xListComposite*    getParent();

 // 자식을 추가한다.
 void        insertChild(Type* child);

 // 자식들을 순환 호출한다.
 template <typename Function>
 void        order(Function& func);
 // 자식들을 순환으로 찾는다.
 template <typename Function>
 Type*        find(Function& func);

 xListComposite*      parent_;
};

// 생성자
template <typename Type, typename Pointer>
xListComposite<Type, Pointer>::xListComposite()
{
}

// 소멸자
template <typename Type, typename Pointer>
xListComposite<Type, Pointer>::~xListComposite()
{
}

// 부모 composite를 설정한다.
template <typename Type, typename Pointer>
void   xListComposite<Type, Pointer>::setParent(const xListComposite* parent)
{
 parent_ = parent;
}

// 부모 composite를 반환한다.
template <typename Type, typename Pointer>
xListComposite<Type, Pointer>* xListComposite<Type, Pointer>::getParent()
{
 return parent_;            
}

// 자식을 추가한다.
template <typename Type, typename Pointer>
void   xListComposite<Type, Pointer>::insertChild(Type* child)
{
 Pointer ptr(child);
 ptr->setParent(this);
 push_back(ptr);
}

// 자식들을 순환 호출한다.
template <typename Type, typename Pointer, typename Function>
void   xListComposite<Type, Pointer, Function>::order(Function& func)
{
 func(this);
 for (iterator i = begin(); i != end(); i ++)
  i->order(func);
}

// 자식들을 순환으로 찾는다.
template <typename Type, typename Pointer, typename Function>
Type*   xListComposite<Type, Pointer, Function>::find(Function& func)
{
 if (func(this))
  return this;

 for (iterator i = begin(); i != end(); i ++)
  if (i->find(func))
   return i->get();
}


/// leaf.h
                 
#include "composite.h"
// composite를 이용하는 노드를 생성한다.
class  xLeaf : public xListComposite<xLeaf>
{
public :
 xLeaf(const char* name)
 {
  name_ = new char [128];
  strcpy(name_, name);          
 }

 ~xLeaf()              
 {
  delete name_;
 }

 char*    name_;          
}; // xLeaf

/// program.cpp

#include "leaf.h"

struct  Ldisplay
{
 void operator () (xLeaf* leaf)
 {
  std::cout << leaf->name_;
 }
};

struct  Lfind
{
 Lfind(char* find)
 {
  strcpy(find_, find);
 }
 bool operator () (xLeaf* leaf)
 {
  return strcmp(leaf->name_, find_) == 0;
 }
 char  find_[128];
};

void  main()
{
 xLeaf root("과일");

 root.insertChild(new xLeaf("사과"));
 root.insertChild(new xLeaf("바나나"));
 root.insertChild(new xLeaf("복숭아"));
 root.insertChild(new xLeaf("배"));

 xLeaf* leaf = root.find(Lfind("사과"));
 leaf->insertChild(new xLeaf("부사"));
 leaf->insertChild(new xLeaf("국광"));

 root.order(Ldisplay());
}

// 버그 수정및 결과 예측

Tag |