If you don't care about loop order in for loop then instead this

for( i=0;  i<SIZE;  i++)

you can use

for( i=SIZE; i--; )

and the loop should be faster

>i'd just write a new function and get it over with
That's one way to go about it, but since fgets is already there and is presumably written with performance in mind, it's smarter to make use of it:

char *reads ( char *s, size_t limit, FILE *stream )
{
  if ( fgets ( s, limit, stream ) == NULL ) {
    return NULL;
  } else {
    char *newline = strchr ( s, '\n' );
 
    if ( newline != NULL )
      *newline = '\0';
 
    return s;
  }
}

It's also easier to verify correctness when you use the standard library instead of trying to rewrite it.

I Think this approach will save the time for developer but it will consume more cpu cycles, It's true that fgets enters new line character at the end of string so take the length of string and modify last character to '\0' , I would suggest

char *reads ( char *s, size_t limit, FILE *stream )
{
  if ( fgets ( s, limit, stream ) == NULL ) {
    return NULL;
  } else {
    int len = strlen(s);
   s[len-1] = '\0';
    return s;
  }
}

Correect me if i am wrong:lol:

Suneel

and the loop should be faster

Micro-optimization should be the last item on your list of things to do.

Correect me if i am wrong:lol:

You need to check for the existance of a newline before you attempt to blow it away. Or just go with what was written -- when waiting for user input, you aren't doing anything really speedy anyways.

Micro-optimization should be the last item on your list of things to do.

If working on PC - yes
but if working on 8 - bit TV proccesors - no

If working on PC - yes
but if working on 8 - bit TV proccesors - no

I've only run into the "need" to do this for parts with less than 2k of code space. Down in that realm, you really ought to consider assembly anyway.

But first, consider that the audience here is 99% PC folks. Not that that needs to mean anything...

But second, remember that no C construct can be generalized as being "faster" or "more efficient". What's good advice in the '60's and '70's may be bad advice today. (I seem to remember "common knowledge" was never to compare to zero.) Likewise, what is good advice in the '80's and '90's may not be solid advice today. (Like this.)

For example, with no optimiztions comparing these two constructs it could be argued that this code generates less efficient output for the loop.

;	
   ;	void foo(int SIZE)
   ;	
	push      ebp
	mov       ebp,esp
	push      ebx
	push      esi
	mov       esi,dword ptr [ebp+8]
   ;	
   ;	{
   ;	   int i;
   ;	   for ( i=0;  i<SIZE;  i++ )
   ;	
?live1@16: ; ESI = SIZE
@1:
	xor       ebx,ebx
	cmp       esi,ebx
	jle       short @3
   ;	
   ;	   {
   ;	      printf("%d\n", i);
   ;	
?live1@32: ; EBX = i, ESI = SIZE
@2:
	push      ebx
	push      offset s@
	call      _printf
	add       esp,8
	inc       ebx
	cmp       esi,ebx
	jg        short @2
   ;	
   ;	   }
   ;	}
   ;	
?live1@48: ; 
@3:
@5:
	pop       esi
	pop       ebx
	pop       ebp
	ret 
_foo	endp
_bar	proc	near
?live1@64:
   ;	
   ;	void bar(int SIZE)
   ;	
	push      ebp
	mov       ebp,esp
	push      ebx
   ;	
   ;	{
   ;	   int i;
   ;	   for ( i=SIZE; i--; )
   ;	
@6:
	mov       ebx,dword ptr [ebp+8]
	jmp       short @8
   ;	
   ;	   {
   ;	      printf("%d\n", i);
   ;	
?live1@96: ; EBX = i
@7:
	push      ebx
	push      offset s@+4
	call      _printf
	add       esp,8
@8:
	mov       eax,ebx
	add       ebx,-1
	test      eax,eax
	jne       short @7
   ;	
   ;	   }
   ;	}
   ;	
?live1@112: ; 
@10:
	pop       ebx
	pop       ebp
	ret 
_bar	endp

If working on PC - yes
but if working on 8 - bit TV proccesors - no

That's true, but this is good practice to write code in such a manner where minimum optimization required:)

Fantastic guys - you learn so much from just browsing.

The Guru
G3 Creative Scotland

This is one of the way more obvious tips but people always seem to not end up doing this. When creating a code (any code be it c++ - HTML) it is extremely time consuming to find errors if you do not keep it well organized.
That means that first and foremost, your brackets are key. Don't add in excess because its just another thing to keep track of and if ur coding I'm sure u want no more of that.
Second, double space almost everwhere becuase it makes the code 10x easier to read.
Third. If you are concentrating on a certain area of code a great thing to do is add // to the obsolete parts.
*side note: if trying to build a code that forms thousands of random numbers per minute and outputs them into notepad (or other) with the intent to crash someone else's computer, make sure it con't crash your own first lol.

t is extremely time consuming to find errors if you do not keep it well organized.

That means that first and foremost, your brackets are key. Don't add in excess because its just another thing to keep track of and if ur coding I'm sure u want no more of that.

If you mean skip full bracing, this would be contrary to common wisdom. Full bracing is always preferred.

Third. If you are concentrating on a certain area of code a great thing to do is add // to the obsolete parts.

Again, unless you can add more detail, this is contrary to common wisdom. Using the preprocessor would be preferred.

nah, sorry that did seem a bit off. What I meant was that you should try to only use the correct amount of brackets instead of adding a whole bunch of brackets at the bigging, a whole bunch at the end, and then just trying to fill in. I know it sounds stupid but I know about 2 or 4 people who add brackets before they even start their actual code. I understand that a lot of brackets are neccesary for a functioning code.

I totally agree to what Jerry Jongerius says:

Use a debugger only as last resort. Having to resort to a debugger means your programming methodologies have failed.

commented: Good Tip ~~ SunnyPalSingh +3

I totally agree to what Jerry Jongerius says:

I guess everyone has heard about the Promo event :cheesy: (just kidding)

For anyone intrested in actually saving time while coding and to know of the best programming practices i actually recommend "The C++ programming languguage" by the inventor of C++.

Personally i feel that the code should be organized in the following way:

1. Header file (one per class) and each header having minimalistic clutter. I personally feel that developing good programming practices is a matter of experience, the more you are exposed everyday to correct modular programming practices the more your skills will be honed. Just having the knowledge of modular programming practices does not suffice. (Header.h)

2. Implementation of Header file (Header.cpp)

3. Driver file which utilises the above two files (Driver.cpp)

Hope it helped, bye.

I guess everyone has heard about the Promo event :cheesy: (just kidding)

What does this mean? Is this an inside joke?:cry:

What does this mean? Is this an inside joke?:cry:

Even I am not sure what he meant but I didn't ask because that would have spoiled his fun :D

Even I am not sure what he meant but I didn't ask because that would have spoiled his fun :D

See Wolfpack's signature...

See Wolfpack's signature...

Ah, now I get it.
He recently changed the signature but this tip came before that :mrgreen:

Use a descriptive name for the type. If you are having difficulty in finding a name for the type, you should do some more research about the type. You still don't know enough about what you want to implement.

Not sure if this belongs here, but non-the-less it has saved me LOT of time when I've to work with someone else's code. :)
Use Astyle to format the C, C++, C#, and Java code.
Download
Documentation
Project Home

DISCLAIMER:
Be warned, if you're scared of blind tool runs that modify code, don't use this. If you use it on production/customer-release code be sure to test. :).

Post your tips for making life easier in C and C++. I'll start:

Standard vector object initialization

The biggest problem with the standard vector class is that one can't use an array initializer. This forces us to do something like this:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  v.push_back(1);
  v.push_back(2);
  v.push_back(3);
  v.push_back(4);
  v.push_back(5);

  // Use the vector
}


Anyone who's had the rule of redundancy pounded into their head knows that the previous code could be wrapped in a loop:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  vector<int> v;

  for (int i = 1; i < 6; i++)
    v.push_back(i);

  // Use the vector
}


However, it's not terribly elegant, especially for a vector of complex types. So, Narue's first timesaving tip for C++ is to use a temporary array so that you can make use of an initializer. Because the vector class defines a constructor that takes a range of iterators, you can use the array to initialize your vector:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
  int a[] = {1,2,3,4,5};
  vector<int> v(a, a + 5);

  // Use the vector
}

So here's what happened.
I was on DaniWeb getting help, and while waiting on someone to reply I looked through the sticky threads. I sent my C++ professor the link to Performance Tips and this thread on Thursday (i think). He sent me a message back saying he liked the one about vector something or other.
So on Friday morning he tells the class he added two slides (he uses powerpoint with most of his lectures), and one of them was because of a tip on the website I go to (daniweb :)). I attached one of the slides he added.

Congrats Narue! :D

using boost.assign http://www.boost.org/libs/assign/doc/index.html is the easiest way to fill containers; and it also works with containers other than vector<>.

#include <vector>
#include <list>
#include <map>
#include <string>
#include <boost/assign.hpp>
using namespace std;
using namespace boost::assign;

int main()
{
  vector<string> strings = list_of("abcd")("efg").repeat(5,"hi")("jkl") ;
  // "abcd" "efg" "hi" "hi" "hi" "hi" "hi" "jkl"
  strings += "mnop", "qrs", "tuvwx", "yz" ;
  // "abcd" "efg" "hi" "hi" "hi" "hi" "hi" "jkl" "mnop" "qrs" "tuvwx" "yz"
  
  list<int> numbers = list_of(100).repeat(7,22)(75)(80)(85)(90)(83) ;
  numbers += 555, 666, 1, 2, 3, repeat(4,99), 56, 75, 80 ;
  
  map<string,int> pbook = map_list_of("abcd",100)("efg",75)("hi",83) ;
  insert(pbook)("mnop",555)("qrs",4)("tuvwx",999)("yz",56) ;
}

where is narue? even if daniweb does not miss her, the c++ forum does.

Referring to Mr.BountyX tips on time saving ,,
"I know this may not seem like a super time saving technique, but the way you name your variables will help save time and reduce compile time errors.."

Yes indeed. This helps a lot.

Variable Naming conventions are very important in programming and it also reduces the code reviewing time a lot .

Eg:

consider a program which has

int RecId;

For a novel programmer who is looking at your code , may wonder at a particular point of the code about the data type of the variable.
b'coz "RecId" doesnt anyhow says whether it is a integer or string or char .

Some thing like this would help the programmer easily to understand ...

int nRecID.

The ' n ' at the begin says it as integer. so when ever someone look at it he can easily understand
datatype of the variable instead of looking at the declaration again ..

Famous conventions:
eg:

int nNumber;
string sData;
float fVal
CString csData;

For Global variable's prefix it like
' g_VARIABLENAME''

C++ STL [

vector<int> vec_nVal;
// Store  elements into vector ...
// Accessing vector elements :

int ninitialize;
for ( ninitialize = 0 ; ninitialize < vec_nVal.size() ; ninitialize++ )
{
   int nVal = vec_nVal[ninitialize];

   cout<< nVal ;
}

Two Time saving Tips;
1. Try avoiding function call at the for loop condition check

for ( ninitialize = 0 ; ninitialize < vec_nVal.size() ; i++ )

Function calls are costlier . So in the above code , for every iteration,vector::size() function will be called , which is not recommended
unless or otherwise if you know that vector size is going to change inside the loop .

For example : If the vector contains 100K elements then vector::size will be called 100K times.

so the best practice will be like , getting the size of the vector before the loop begin and substitute the variable accordingly . something like this ...

int nVecSize = vec_nVal.size();
for ( ninitialize = 0 ; ninitialize < nVecSize  ; i++ ) "

2 . Use Iterators One of the main concept of stl's are iterator. use it when ever required .

The above sample program can be written like this for the best performance and time saving .

vector<int>::iterator itrNumber;
itrNumber = vec_nVal.begin();

while( itrNumber != vec_nVal.end())
{
         int nVal  =*(itrNumber );
         cout<<nVal;
        itrNumber++
}

by using iterator the element retrieval time will be faster when compare to the previous one[ vector[] ] .

The same holds good for all stl containers . (eg:stl::map)

I am so sure that the above one will improve your performance and save your time leap and bound if you are using it excessively.

W.r.t std::vector.... Especially while loading ( doing a push_back )if u already know the the number of elements to be inserted then u can reserve it before u start loading. Use the reserve(...) function.

This was asked in another forum I go to and I came up with the following:

Reading contents of a file directly to a vector

#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

int main( void ) {
  std::ifstream in( "shorts.txt", std::ios::binary );

  if ( in ) {
    std::vector< short > vs;
    vs.insert( vs.begin(), std::istream_iterator<short>(in), std::istream_iterator<short>() );
    std::copy( vs.begin(), vs.end(), std::ostream_iterator<short>(std::cout, "\n"));
  }

  return 0;
}

It's along the same lines as Naure's 'printing vector contents without a loop' trick. Use with caution though. Especially if you have a mix of types:

#include <fstream>
#include <vector>
#include <string>
#include <algorithm>

int main( void ) {
  std::ifstream in( "shorts.txt", std::ios::binary );

  if ( in ) {
    std::vector<short>        vshort;
    std::vector<std::string>  vstr;


    // Read shorts until fail
    vshort.insert( vshort.end(), std::istream_iterator<short>(in),       std::istream_iterator<short>() ); 
    // Clear stream
    in.clear();

    // Read strings until fail, inadvertently reads to end of file. 
    vstr.insert( vstr.end(),     std::istream_iterator<std::string>(in), std::istream_iterator<std::string>() );

    std::copy( vshort.begin(), vshort.end(), std::ostream_iterator<short>(std::cout, "\n") );
    std::copy( vstr.begin(),   vstr.end(),   std::ostream_iterator<std::string>(std::cout, "\n") );
  }

  return 0;
}

Will store numbers in the vector of strings until it fails. Then after clearing the stream it'll read in the rest of the contents until finished. But of course this is the case in all file IO.

tips
1 . use loops
2. use pointer
3.use functions
4. use method overloading
5 use typedef for initialisation

commented: typedef for initialization? WTF is that supposed to mean? -2
commented: Spammer. -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.