Why do I have to specify data type each time in C?

后端 未结 11 2750
温柔的废话
温柔的废话 2020-12-12 18:17

As you can see from the code snippet below, I have declared one char variable and one int variable. When the code gets compiled, it must identify t

11条回答
  •  心在旅途
    2020-12-12 18:42

    Because in the printf you're not specifying data type, you're specifying data format. This is an important distinction in any language, and it's doubly important in C.

    When you scan in a string with with %s, you're not saying "parse a string input for my string variable." You can't say that in C because C doesn't have a string type. The closest thing C has to a string variable is a fixed-size character array that happens to contain a characters representing a string, with the end of string indicated by a null character. So what you're really saying is "here's an array to hold the string, I promise it's big enough for the string input I want you to parse."

    Primitive? Of course. C was invented over 40 years ago, when a typical machine had at most 64K of RAM. In such an environment, conserving RAM had a higher priority than sophisticated string manipulation.

    Still, the %s scanner persists in more advanced programming environments, where there are string data types. Because it's about scanning, not typing.

提交回复
热议问题