불리언과 분기
Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 7번째.
C++의 std::string에는 비어 있는지 확인하는 API가 있으며, 암시적 bool 변환은 지원하지 않습니다. C 문자열은 보통 포인터를 통해 접근합니다. 포인터가 null이 아니면 빈 문자열도 조건식에서 참으로 평가됩니다.
0과 null 포인터는 조건식에서 거짓입니다. 빈 문자열을 가리키는 포인터도 여전히 null이 아닙니다.
C++ 예제
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
int main(){
std::string s="";std::cout << std::boolalpha << s.empty() << "\n";
}
C++ 출력:
trueC 예제
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
const char *s=""; printf("%s\n",s?"true":"false");
return 0;
}
C 출력:
true챌린지
쉬움음수 입력에는 -1을, 0에는 0을, 양수 입력에는 1을 반환하세요.
잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 공개된 잠금 상태의 main.c에서 직접 호출하는 선언된 공개 API와 호환되도록 유지하세요. 다른 main을 추가하지 마세요. 작업에서 범위를 명시적으로 확인하지 않는 한, 숫자 작업의 모든 테스트 값은 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 드라이버 코드가 표시된 경우 입력 파싱과 출력을 담당합니다.
직접 해보기
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int n=0;if(scanf("%d",&n)!=1)return 1;printf("%d\n",sign_of(n));return 0;}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C의 모든 레슨
직접 연습해 보세요: 온라인 C 컴파일러