본문 바로가기

C Language

while(*str) 이 있는데 if(*str)이 있는이유 | The reason of using if(*str) despite of while(*str) syntax below

아래에 while(*str)이 있는데 왜 if(*str)이 있는걸까요?

이 코드에서 if (*str) 검사는 불필요해 보일 수 있지만, 실제로는 중요한 역할을 합니다. 그 이유는 다음과 같습니다:

  1. 빈 문자열 처리
    • if (*str) 검사는 첫 번째 단어 이후에 추가 문자가 있는지 확인합니다.
    • 만약 입력이 단일 단어라면, 이 검사로 인해 추가 공백이 출력되지 않습니다.
  2. 불필요한 공백 방지
    • 이 검사가 없다면, 단일 단어 입력 시에도 단어 뒤에 추가 공백이 출력될 수 있습니다.
  3. 로직의 명확성
    • if (*str) 검사는 첫 번째 단어 이후의 처리를 명확히 구분합니다.
    • 이는 코드의 가독성과 의도를 더 명확하게 만듭니다.

예를 들어:

  • 입력: "Hello"
    • if (*str) 있을 때: "Hello" (추가 공백 없음)
    • if (*str) 없을 때: "Hello " (끝에 불필요한 공백)
  • 입력: "Hello World"
    • 두 경우 모두: "World Hello"

따라서, if (*str) 검사는 불필요해 보이지만 실제로는 프로그램의 정확성과 출력의 일관성을 유지하는 데 중요한 역할을 합니다.

 

 

In this code, the if (*str) check might appear unnecessary, but it actually plays a crucial role. Here's why:
Empty String Handling
The if (*str) check verifies if there are additional characters after the first word.
If the input is a single word, this check prevents additional spaces from being output.
Preventing Unnecessary Spaces
Without this check, extra spaces might be output even for single-word inputs.
Clarity of Logic
The if (*str) check clearly delineates the processing of the first word from subsequent words.
This enhances the code's readability and intention.
For example:
Input: "Hello"
With if (*str): "Hello" (no extra space)
Without if (*str): "Hello " (unnecessary space at the end)
Input: "Hello World"
In both cases: "World Hello"
Therefore, while the if (*str) check might seem superfluous, it actually plays a vital role in maintaining the program's accuracy and output consistency.