常量浮點數的大小為 8 個位元組,而變數浮點數僅為 4 個位元組。
#include <stdio.h>
#define x 3.0
int main(){
printf("%d", sizeof(x));
return 0;
}
這也適用于常量 char(給出 4 個位元組),而 char 變數只給出 1 個位元組。
uj5u.com熱心網友回復:
我認為這個問題已經在之前的幾篇文章中得到了回答。基本思想是:
A) 在 C 中考慮這個程式:
#include <stdio.h>
#define x 3.0 /* without suffix, it'll treat it as a double */
#define y 3.0f /* suffix 'f' tells compiler we want it as a float */
int main() {
printf("%ld\n", sizeof(x)); /* outputs 8 */
printf("%ld", sizeof(y)); /* outputs 4 */
return 0;
}
基本上, double 比 float 具有更高的精度,因此在有歧義的情況下更可取。因此,如果您宣告沒有后綴“f”的常量,它會將其視為雙精度。
B)現在看看這個:
#include <stdio.h>
#define x 'a'
int main() {
char ch = 'b';
printf("%ld\n", sizeof(x)); /* outputs 4 */
printf("%ld", sizeof(ch)); /* outputs 1 since compiler knows what it's
exactly after we declared & initialized var
ch */
return 0;
}
該常量值 ('a') 被轉換為它的 ASCII 值 (097),它是一個數字文字。因此,它將被視為整數。請參閱此鏈接了解更多詳情: https ://stackoverflow.com/questions/433895/why-are-c-character-literals-ints-instead-of-chars#:~:text=When the ANSI committee first,of achiencing the same thing。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460297.html
上一篇:靜態變數是否將自動變數中的任何內容更改為const?
下一篇:為什么將方法分配給C#中的變數?
