수안이의 컴퓨터 연구실

  • Mainpage
  • About Me
  • Tags
  • Metapage
  • Notice
  • Location
  • Keywords
  • Guestbook
  • Admin
  • Write an Article
  • Total | 1620994
  • Today | 374
  • Yesterday | 482

Programming/C++2008/04/26 15:56

C++ Programming Tips

Site : http://www.devarticles.com/c/a/cplusplu ··· ing-tips

In this article, I give you programming tips that can improve your C++ code. I will cover use of parentheses, long expressions, modifying objects, and more. By the time I'm done, you will hopefully have learned a few ways to make your code faster as well as easier to understand and maintain.

C++ Fundamentals

Use of parentheses

Consider this expression without parentheses:

and the equivalent with parentheses:

Both expressions perform exactly the same computation, but the meaning of the second one is clearer, since parentheses are used.

Expressions (like the two above) are evaluated by following the rules of precedence. The above expressions are the same. So from a technical point of view, you do not need parentheses. However, including parentheses makes the order of evaluation explicit to the person maintaining your code (even you).

Long expressions (Style)

We often need to write long expressions that will not fit on one line of the screen. For example, the expression

is quite long and will not fit on one line of the screen. A good way to break a long expression into a multiline expression is to use continuation lines. These lines should always begin with an operator and be indented one space. Both of these serve to signal the reader that the line is a continuation of the previous line. So the above example can be written as follows:



As another example, the expression

can be better written as

Speed versus clarity and correctness

One rule of thumb in programming is that 90 percent of a program’s running time is spent on 10 percent of the code. So without some idea of where a program spends most of its time, most changes to a program to speed it up will have little or no effect on the overall running time. While speed is important, clarity (presentation of the code) and correctness are always more important. We should never sacrifice clarity and correctness for speed.

Hot spots are where a program spends most of its time. If speed becomes an issue, a more effective approach is to complete the writing of the program and then order a tool which can be used to identify the hot spots of the program. The hot spots can then be tuned (recoded) to reduce the running time of the program.

Increment and decrement operators (style)

Always use increment and decrement operators to reduce the length of your code. This also portrays you as a mature programmer.

So for example, you should write

instead of

or write

instead of

where i is a C++ variable.

Watch out for operator precedence on long expressions.

Function Usage Basics and Libraries

Controlling the evaluation of assert invocations

The default behavior of an assert invocation is to evaluate assertions. The macro NDEBUG must be undefined for the expression in an assert invocation to be evaluated. Through the use of the following preprocessor statement, the evaluation of subsequent assertions can be turned off.

In some cases, evaluation of assertions can be turned on again through the use of the following preprocessor statement:

This process works because the actions that an assert invocation performs are nested within a conditional evaluation directive that checks whether NDEBUG is defined. It is a good practice to include the definition of NDEBUG at the start of a program that is distributed to users.

Safe input type

Professional software normally extracts its input in character form. This input is then validated and converted to the desired form (e.g. int). This provides a safe way of extracting data. If you do not respect this, you may suffer from the following consequence: if an int is required and the user accidentally types in a non-digit, the program might terminate with an error message that the user does not understand.

Efficiency in Using Constant Reference Parameter

If you pass an object by value to a function, a copy of the object is first made and then passed to the called function. For large objects, copying can add considerable overhead to the program and may also adversely affect the performance of the program. For such objects, you can obtain efficiency and retain safety by passing the object as a constant reference parameter, such as the following:

ReturnValue functionName(const type &objectName)

The const modifier ensures that the called function does not modify the actual object.

Abstract Data Types

Developing object-oriented programs is typically simpler than developing procedure oriented programs. For example, member functions generally have a smaller parameter list than non-member functions because there is no need to pass the data to member functions.

Since well-written member functions ensure that the data members are correctly initialized and updated, other program functions do not need to validate whether they are using proper object values. The access protection provided by encapsulation also ensures that clients use the public interface and not side effects of the library implementation that may continue as the implementation is modified over time.

Rule of minimality

The rule of minimality states that unless a behavior is needed, it should not be part of the Abstract Data Type. A corollary of this rule is the Class Minimality Principle, which states that if a function or operator can be defined such that it is not a member of the class, then do not make it a member. This practice makes a non-member function or operator generally independent of changes to the class’s implementation.

Character strings or string class strings

If you use the string class, you have a more extensive set of capabilities than if you use character strings.

Generic vector extraction

Consider the following:


The syntax template <class T> indicates that what follows is a generic form. In this situation, the form of the function is given. This function template allows different functions to be instantiated based on the particular type of vector used as the actual parameter. For example, if we have the following definitions:

to be defined and invoked.


Accessing multidimensional arrays

Multidimensional arrays are stored in row-major order. Often contiguous sections of memory, called pages, are brought in with the expectation that values near a desired value are more likely to be referenced than values defined elsewhere in memory. Since a page is contiguous memory, it is more likely to contain a complete row than a complete column. So it is generally more efficient to process array elements row-by-row rather than column-by-column. This efficiency comes about in how memory values are brought into the central processing unit, as explained above.

Pointer strength

The ability to access and change the value of an object whose name is not part of the assignment statement is the feature that makes pointer objects so powerful. This capability is most often used for dynamic objects.

Inheritance: Using data member initialization list

There are two ways to initialize data members when implementing the constructor of a class. One way is to invoke the constructor for the data member via the data member initialization list. The other method is to invoke the data member’s mutator from within the body of the constructor. With the second method, the data member’s default constructor is invoked to construct an object with default values, then the mutator is called to overwrite the default values with initial values. Using the first method, the data member is constructed with the appropriate initial values. As you can see the second method is more efficient, because it is done during construction.

Templates and Polymorphism

Automatic subscript checking for vector elements and other list elements

The vector class template provides a member function, which is:

at().

The function expects an index value as its parameter, say i. If the index is valid (exists), a reference to the ith element of the vector is returned. Otherwise, an exception is generated; the program stops, giving an error message that the user does not understand. You can use inheritance to derive a class that overloads the subscript operators so that index checking is automatically performed in conjunction with the subscript operators. To solve this problem, a template class named protectVector is given below.



Assume reuse

If you are defining a class, unless you know it can never serve as a base class for a derive class, give the class a virtual destructor. In this way, all derived destructors will also be virtual and then, whenever an object is deleted, the correct destructor will be invoked, regardless of the context.

All these tips are what I have gathered, based on my experience and the experience of expert programmers. Here's hoping you put them to good use.

"C++" 카테고리의 다른 글
  • C++ Preprocessor: Always Assert Your Code Is Right (0)2008/04/26
  • C++ Preprocessor: The Code in the Middle (0)2008/04/26
  • C++ Programming Tips (0)2008/04/26
  • C++ Preprocessor: Always Assert Your Code Is Right (0)2007/07/30
  • C++ Preprocessor: The Code in the Middle (0)2007/07/30
2008/04/26 15:56 2008/04/26 15:56
Posted by webdizen
Tags C++Keyword C++, Programming
No Trackback No Comment

Trackback URL : http://www.webdizen.net/blog/trackback/3206

Leave your greetings.

[로그인][오픈아이디란?]

«Prev  1 ... 76 77 78 79 80 81 82 83 84 ... 2998  Next»

RSS HanRSS
Blog Image
webdizen
이 곳은 컴퓨터에 대해 연구하고, 공유하고, 소통하기 위한 연구실입니다. 개인적으로는 OLAP, Data Mining, Semantic Web, Data Modeling에 대해서 연구하고 있습니다.

Categories

전체 (2998)
Webdizen (134)
Life (6)
Diary (16)
Blog (9)
IDEA (1)
Travel (10)
Book (14)
Photo (7)
Movie (7)
Music (13)
Leisure Sports (10)
Funny (5)
Hardware (119)
Software (120)
Windows (5)
Unix & Linux (119)
Installation (4)
Kernel (10)
System (34)
Develop (22)
X-Window (0)
Applicaton (31)
Security (4)
Framework (2)
Hadoop (2)
Programming (805)
Algorithm & Data Structure (1)
Assembly (38)
UNIX/Linux C (95)
C++ (128)
STL (4)
Java (38)
Win32 API (92)
ATL/COM (44)
MFC (151)
.NET (26)
WCF/WPF (4)
C# (28)
Network Programming (17)
Database Programming (12)
OpenGL / DirectX (13)
Multimedia Programming (0)
Game Programming (21)
Parallel Distributed Progra... (0)
Reverse Engineering (0)
Debugging (9)
Python (1)
Ruby (1)
Ruby on Rails (1)
QT (4)
GTK (0)
JSP (0)
PHP (6)
ASP.NET (6)
ASP (3)
Development (28)
Useful Library (2)
Data Modeling (0)
Database (105)
Oracle (4)
MSSQL (41)
MySQL (2)
Data Warehouse (2)
Data Mining (3)
Network (66)
Web (78)
DHTML (4)
XHTML (1)
Javascript (1)
CSS (1)
AJAX (9)
XML (11)
Flex (1)
Silverlight (3)
Security (91)
DoS (1)
Kernel (10)
Scanning (3)
Sniffing (0)
Spoofing (4)
Overflow (28)
Web (11)
Shell (10)
Format String (14)
Window (2)
Embedded (70)
Multimedia (27)
Mobile (14)
Graphic (24)
Management (633)
Knowledge (581)
Hadoop (0)

Notice

  • 메타 블로그 사이트에 등록
  • 새해 맞이 블로그의 변화
  • 블로그 명칭 변경
  • 도메인(www.webdizen.net) 구...
  • TEXTCUBE 1.6.1로 업그레이드...

Tags

  • Statistical
  • CVS
  • 홍보동영상
  • 프로세스 복사본
  • 까벨렐로 리앙트
  • Port
  • 의과대학
  • C#
  • 쿼리 디자인
  • 보드카
  • Singletion Pattern
  • OLTP
  • 256Color
  • 함수 포인터
  • new
  • 습관
  • Performance
  • 학군단
  • 백록관
  • 성능 모니터

Recent Articles

  • ASCII Code의 CRLF 제거 방법.
  • Hadoop 에서 c++ API 이용시....
  • Ubuntu Linux에서 Hadoop 구....
  • 내 심장을 한껏 뛰게한 "국가....
  • 스타 스키마 데이터베이스 설....

Recent Comments

  • ■ 온라인카지노 ▶ http://L....
    asdf 11/21
  • 그리고 혹시 해외여행자보험....
    kim 11/05
  • ★★실제 바다게임장과 똑같....
    asdf 11/04
  • sbsyama.co.to← 짱5000만당....
    asdf 11/04
  • ♡KicaZ??o(???) 바카라사....
    fdsf3fass 11/03

Recent Trackbacks

  • 파일 열기/저장하기 CFileDialog.
    은마군의 나태블록 02/11
  • World IT Show 2008.
    상우 :: Oranzie's BLOG 2008
  • cvs서버 설치하기.
    3인3색 2008
  • 속속 공개되는 Google Chart....
    PHP와 Web 2.0 2007
  • 마방진을 구하는 프로그램.
    Oranzie's BLOG 3 2007

Archive

  • 2009/09 (3)
  • 2009/08 (1)
  • 2009/03 (1)
  • 2009/02 (9)
  • 2009/01 (13)

Calendar

«   2009/11   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          

Bookmarks

    • Administration
      • IIS.NET
      • NTFAQ
      • OS의 모든 것
      • 리눅스포털
    • Database
      • SQL Server Central
      • SQL Team
    • Development
      • .NET Heaven
      • ASP Alliance
      • ASP.NET 2.0
      • Bullog.net
      • C# Corner
      • C++ (C PlusPlus.com)
      • C++ Reference
      • CodeGuru
      • CodePlex
      • DebugLab
      • Dev Articles
      • Devpia
      • DotNet Junkies
      • DotNet Zone
      • Driver Online
      • GOSU.NET
      • HOONS 닷넷
      • Joinc 팀블로그
      • KOSR
      • MSDN Home Page
      • OSR Online
      • Sky.ph - 개발자 커뮤니...
      • TAEYO.NET
      • The Code Project
      • WindowsClient.net
      • 김상욱의 개발자 Side
      • 조인시 위키
    • Human Networks
      • belief21c's e-space
      • I think I can
      • Invisible Rover's Blog :D
      • Rodman®
      • ■ Feel So Good~! ■
      • 까만 나비
      • 나를 가꾸는 시간.
      • 나만의 즐거움~~!
      • 단녕
      • 상우 :: Oranzie's BLOG
    • Information Technology
      • Microsoft TechNet
      • 지디넷코리아 - 글로벌...
    • Security
      • FoundStone
      • milw0rm
      • NewOrder
      • OpenRCE
      • Phrack.org
      • Reverse Engineering b1...
      • Reverse Engineering Team
      • RootKit
      • SecurityFocus
      • SecurityXploded by Nag...
      • Wow Hacker
      • Zone-H
Textcube
Louice Studio Inc.
Powered by Textcube. Original designed by Tistory.