[英]Is automatic vertex attribute assignment guaranteed to be in the correct order?
[英]Is there a guaranteed order of assignment in scanf?
我遇到了一些代碼,並且想知道它只是按預期效果工作還是偶然的做法。 考慮以下MCVE( ideone ):
#include <cstdio>
struct dummyStruct
{
unsigned short min[4];
unsigned short max[4];
int dummyBuffer; // This just happens to be here as a real variable in the original code, not just as a buffer.
};
int main()
{
dummyStruct db;
// Note that the size of the short is assumed to be half of that of the %d specifier
sscanf(" 123, 456, 789, 112", "%d, %d, %d, %d", db.min+0, db.min+1, db.min+2, db.min+3);
sscanf("29491, 29491, 29491, 29491", "%d, %d, %d, %d", db.max+0, db.max+1, db.max+2, db.max+3);
db.dummyBuffer = 1234;
printf("%hd, %hd, %hd, %hd\n", db.min[0], db.min[1], db.min[2], db.min[3]);
printf("%hd, %hd, %hd, %hd\n", db.max[0], db.max[1], db.max[2], db.max[3]);
printf("%d\n", db.dummyBuffer);
return 0;
}
標准是否保證了結構的內容,還是這種不確定的行為? 我在N4810中沒有提到這一點 。 或者,如果我們顛倒了變量的順序,例如
printf("%hd, %hd, %hd, %hd\n", db.min[0], db.min[2], db.min[1], db.min[3]);
db.min
的內容db.min
得到保證? 參數的順序(從左到右)是分配的順序嗎? 還要注意,我並不是在問為什么這是不好的做法,即使已定義。 我也不需要評論告訴我不要使用scanf
。 我不是。
在N4810中您沒有提到任何內容,因為涉及到C標准庫時,該規范大部分被推遲到“ ISO / IEC 9899:2011,編程語言-C”中 。 如果我們看一下N1570 (C11草案),它說明了scanf
系列功能:
7.21.6.2 fscanf函數 (強調我的)
10除使用%指定符外,輸入項(或使用%n指令輸入字符數)將轉換為適合於轉換說明符的類型。 如果輸入項不是匹配序列,則指令的執行失敗:此條件是匹配失敗。 除非用*表示禁止分配,否則轉換結果將放置在尚未收到轉換結果的format參數后面的第一個參數指向的對象中。 如果此對象的類型不合適 ,或者無法在對象中表示轉換結果,則該行為為undefined 。
因此,您的示例工作確實是偶然行為,它是由未定義的行為產生的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.