简体   繁体   中英

Why I can't use i/10 in FOR LOOP, C++?

I can't use i/10 in **FOR LOOP, C++. Can you please find why I can't use that!! when I write the code below;

#include <iostream>
using namespace std;
int main()
{
    int sum=0,i;
    cout<<"enter a no.";
    cin>>i;
    for(i;i!=0;i=i/10)
    {
        sum=sum+i%10;
    }
    cout<<"sum="<<sum;
}

After compiling it shows that:-

cpp_2.cpp:8:7: warning: statement has no effect [-Wunused-value]

for(i;i!=0;i=i/10)

Please help me!!

You can, although i = i / 10 can be abbreviated to the arguably clearer i /= 10 .

Your helpful compiler is warning you about the initialisation expression of the for , which is just i , and that is a no-op.

Writing

for (; i; i /= 10)

is equivalent, and will keep the compiler happy. Note that I've replaced the tautologous i != 0 with, simply, i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM