簡體   English   中英

" for (int j = 0; j < n || !putchar('\\n'); j++) " 是如何工作的

[英]how does " for (int j = 0; j < n || !putchar('\n'); j++) " work

找到了這段代碼,負責打印出一個二維數組

for (int i = 0; i < n; i++)
 for (int j = 0; j < n || !putchar('\n'); j++)
  printf_s("%4d", A[i][j]); 

導致在每行末尾打印轉義序列的布爾表達式如何工作?

因為|| ,只有當j < n為假時才會調用putchar函數。 現在, j < n在每一行的末尾都是假的。 這就是為什么你在每一行的末尾得到\\n的原因。

這里有兩件事在起作用:

  1. 邏輯 AND 和 OR 運算符的短路評估語義

  2. !putchar('\\n')將始終為“false”( putchar返回寫入的字符或EOF ,在這種情況下兩者都非零,因此為“true”)

j < n為真時, ||的右側由於短路語義,將不會被評估。 j < n為假時, !putchar('\\n')將被評估,它將打印一個換行符並返回一個“真”值( '\\n'EOF錯誤),這是由於! 變為假,所以整個條件變為假,循環結束。

這是一個混淆的變體

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
    {
        printf_s("%4d", A[i][j]); 
    }
    putchar('\n');
}

我真的建議您不要使用(或更糟的是,編寫)代碼作為問題中顯示的代碼。 混淆不是一件值得驕傲的事情(除非你進入IOCCC )。

if (counter &amp; (1&lt; <j)) mean and how does it work?< div><div id="text_translate"><p> 我正在研究子序列的算法。</p><p> 語句的含義是什么:</p><pre> if (counter &amp; (1&lt;&lt;j))</pre><p> 在以下方案范圍內:</p><pre> void printSubsequences(int arr[], int n) { unsigned int opsize = pow(2, n); for (int counter = 1; counter &lt; opsize; counter++) { for (int j = 0; j &lt; n; j++) { if (counter &amp; (1&lt;&lt;j)) cout &lt;&lt; arr[j] &lt;&lt; " "; } cout &lt;&lt; endl; } }</pre></div></j))>

[英]What does the statement if (counter & (1<<j)) mean and how does it work?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM