简体   繁体   中英

Is i++ or ++i better for this program?

i'm trying to create a program which checks if input is is an int or a string.

This is the code:

// CPP program to check if a given string 
// is a valid integer 
#include <iostream> 
using namespace std; 
  
// Returns true if s is a number else false 
bool isNumber(string s) 
{ 
    for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false; 
  
    return true; 
} 
  
// Driver code 
int main() 
{ 
    // Saving the input in a string 
    string str = "6790"; 
  
    // Function returns 1 if all elements 
    // are in range '0-9' 
    if (isNumber(str)) 
        cout << "Integer"; 
  
    // Function returns 0 if the input is 
    // not an integer 
    else
        cout << "String"; 
} 

I wanted to ask that whether i++ or ++i is better for this loop and why?

for (int i = 0; i < s.length(); i++) 
        if (isdigit(s[i]) == false) 
            return false;

THANK YOU!

I prefer the form ++i in C++, because i may be an iterator or other object with overloaded operator++ . In those cases, the form i++ generates a temporary object to hold the previous value of i , while the form ++i does not. The compiler may optimize away that temporary object, but it's not required to, and in some cases may not be allowed to.

So, ++i is slightly better than i++ as the former need not retain the initial value and recheck it. It is one of the very few instances where time optimization and memory optimization occur simultaneously. But the difference is too small to be noted, just 4 bytes. Also, the time difference is negligibly small.

You would essentially get the same answer in your example but might receive a minute time and memory optimization while using ++i .

Since the datatype of i is int, it doesn't matter if you use i++ or ++i. If its a large class iterator, ++i is faster than i++. Its a good practice to use ++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