Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C와 C++에서 다른 결과를 생성하는 프로그램 작성

<시간/>

여기에서 C 또는 C++ 컴파일러로 컴파일된 경우 다른 결과를 반환하는 일부 프로그램을 볼 수 있습니다. 그러한 프로그램을 많이 찾을 수 있지만 여기에서는 그 중 일부에 대해 논의합니다.

C 및 C++에서 문자 리터럴은 다른 방식으로 처리됩니다. C에서는 int로 처리되지만 C++에서는 문자로 처리됩니다. 따라서 sizeof() 연산자를 사용하여 크기를 확인하면 C에서는 4를 반환하고 C++에서는 1을 반환합니다.

C용.

예시

#include<stdio.h>
int main() {
   printf("The character: %c, size(%d)", 'a', sizeof('a'));
}

출력(C)

The character: a, size(4)

C용.

예시

#include<stdio.h>
int main() {
   printf("The character: %c, size(%d)", 'a', sizeof('a'));
}

출력(C++)

The character: a, size(1)

C에서 struct를 사용하면 typedef가 사용될 때까지 사용할 때 struct 태그를 사용해야 합니다. 그러나 C++에서는 구조를 사용하기 위해 태그를 구조화할 필요가 없습니다.

C용.

예시

#include<stdio.h>
struct MyStruct {
   int x;
   char y;
};
int main() {
   struct MyStruct st; //struct tag is present
   st.x = 10;
   st.y = 'd';
   printf("Struct (%d|%c)", st.x, st.y);
}

출력(C)

Struct (10|d)

C++용.

예시

#include<stdio.h>
struct MyStruct{
   int x;
   char y;
};
int main() {
   MyStruct st; //struct tag is not present
   st.x = 10;
   st.y = 'd';
   printf("Struct (%d|%c)", st.x, st.y);
}

출력(C++)

Struct (10|d)

Boolean 타입 데이터의 크기는 C와 C++에서 다릅니다.

C용.

예시

#include<stdio.h>
int main() {
   printf("Bool size: %d", sizeof(1 == 1));
}

출력(C)

Bool size: 4

C++용.

예시

#include<stdio.h>
int main() {
   printf("Bool size: %d", sizeof(1 == 1));
}

출력(C++)

Bool size: 1