Welcome to LearnProgramming.cc.cc

This site is most powerfull when you want to learn more about programming language,hope this site can help you full,enjoy to learn.

Logo Forum Programmer USNI

Ini adalah logo forum programmer Universitas Satya Negara Indonesia tahun 2010-2011.

Forum Programmer USNI 2010-2011

Foto anak anak forum programmer angkatan 2010-2011 dalam acara workshop di Universitas Satya Negara Indonesia.

Learn with different method and solution

Belajar Pemrograman tidak harus serius namun harus dengan santai agar setiap alur logic program dapat berjalan sesuai dengan yang dinginkan.

The Power of programmer

Programer dan bos besar sama-sama berkuasa :D yang membedakan adalah dunianya,programmer adalah BOS di dunia maya,hehe #JOKE.

Teks Berjalan di Posting dengan Efek Marquee



Hey sobat,kali ini saya akan membahas tentang bagaimana cara membuat teks berjalan di posting,cara menjalankan teks ini dengan menggunakan efek marquee. Langsung saja ya..

  • Teks Berjalan Dari Kanan ke Kiri
Ini merupakan format marquee standar agar teks dalam postingan sobat bisa berjalan secara default dari kanan ke kiri. Ini HTMLnya :

<marquee>TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT


  • Teks Berjalan dari Kiri ke Kanan
Format ini kebalikan dari format yang di atas,yaitu teks berjalan dari kiri ke kanan. Ini HTMLnya :


<marquee direction="right">TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT


  • Teks Berjalan Bolak-Balik (Kiri ke Kanan atau Kanan ke Kiri )

Format ini membuat teks berjalan bolak-balik memantul kiri ke kanan dan kanan ke kiri. Ini HTMLnya :

<marquee behavior="alternate">TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

  • Teks Berjalan Dari Bawah Ke Atas
Format ini membuat teks anda berjalan dari bawah ke atas. Ini HTMLnya :

<marquee direction="up">TEKS PUNYA SOBAT</marquee>


Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

  • Teks Berjalan Dari Atas Ke Bawah
Format ini kebalikan dari yang diatas yaitu membuat teks berjalan dari atas ke bawah. Ini HTMLnya :


<marquee direction="down">TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

  • Membuat Text Berhenti Jika Diarahkan Oleh Mouse

Jika sobat arahkan mouse pada teks tersebut maka text tersebut akan berhenti. Ini HTMLnya :


<marquee onmouseover="this.stop()" onmouseout="this.start()">TEKS PUNYA  SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

Anda bisa menerapkan format ini pada ke text berjalan di atas dengan menambahkan kode Html pada tag pembuka.

<marquee behavior="alternate" onmouseover="this.stop()" onmouseout="this.start()">TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

Mengatur Kecepatan Text Berjalan

Untuk mengatur kecepatan menggunakan perintah:

scrollamount="10"

Untuk mengatur kecepatan teks ganti angka pada bertanda petik diatas ("10"), semakin kecil nilai ditulis maka motion akan semakin lambat dan semakin besar nilai yang dibuat juga semakin cepat motion teks yang akan muncul. Ini HTMLnya :

<marquee scrollamount="10">TEKS PUNYA SOBAT</marquee>

Dan Seperti ini contohnya :

TEKS PUNYA SOBAT

Mengatur Batas Ruang Text Berjalan

Untuk mengatur batas ruang menggunakan perintah:

width="100%" height="100"

Badingkan contoh berikut height="40" dan height="80"

Contoh :

<marquee direction="up" width="100%" height="40">TEKS PUNYA SOBAT</marquee>

TEKS PUNYA SOBAT

<marquee direction="up" width="100%" height="80">TEKS PUNYA SOBAT</marquee>

TEKS PUNYA SOBAT

Sekian yang saya dapat jelaskan,jika sobat ada yang kurang mengerti / pahami silahkan bertanya dengan cara mengisi kolom komentar di bawah postingan ini..



Selamat Mencoba...

Trik Membuat Teks Berjalan di Address Bar

Ini ada Tricks membuat tulisan/text sesuai dengan yang kita inginkan di address bar pada Blog kita bisa jalan-jalan. Tujuannya adalah untuk memikat dan menarik pengunjung agar blog kita mendapat nilai lebih dari pengunjung (biar dipikir hebat..:P).

oia,sebelumnya ada yang tau ga ni apa itu address bar??,ini saya kasih tau gambarnya..


ini dia yang namanya address bar...(klo kurang jelas di klik aja gambarnya)



langsung saja ya..

copykan script di bawah ini dan letakkan (paste) tepat di atas kode
(Untuk memudahkan mencari kode tekan tombol keyboard ctrl + f atau F3 pada posisi edit HTML di blogspot).

<script type='text/javascript'>
//<![CDATA[

msg = "studypemrograman.co.cc";
msg = "belajar pemrograman itu mengasikkan..." + msg;pos = 0;
function scrollMSG() {
document.title = msg.substring(pos, msg.length) + msg.substring(0, pos); pos++;
if (pos > msg.length) pos = 0
window.setTimeout("scrollMSG()",200);
}
scrollMSG();
//]]>
</script>


keterangan :

Pada tulisan studypemrograman.co.cc ganti dengan nama blog atau situs atau nama lain sesuai keinginan sobat dan belajar pemrograman itu mengasikkan... juga dapat diganti sesuai kenginan sobat..
sangat mudah bukan??:D,silahkan langsung di praktekkan...



semoga berhasil...

Cara Membuat Widget Berlangganan Email di Feedburner

Widget E-mail Subscribe (berlangganan lewat email) adalah media untuk pengunjung blog agar dapat membaca feeds blog sobat melalui email dan jika anda mempunyai Atikel terbaru akan di kirimkan ke email pengunjung blog sobat yang telah mendaftar email subscribe pada blog sobat dengan cara memasukkan alamat emailnya. Sehingga pembaca yang tertarik dengan artikel kita bisa juga membaca lewat alamat email mereka. Langsung saja ya....
 
 
Ikuti prosedur di bawah ini (wah,serius banget... :P) :
  •  Masuk Situs feedburner.com jika anda belum punya account daftar dulu
  •  Setelah daftar langkah kedua yang harus anda lakukan adalah Sign in
  •  Isi alamat feed blog sobat misalnya http://apri-fh.blogspot.com/feeds/posts/default
          Ganti tulisan apri-fh.blogspot.com dengan alamat blog sobat.
  •  Check Box Im a Podcaster! beri centang bila blog sobat isinya video.
  •  Kemudian tekan tombol Next.
  •  Lalu isi Feeds Title juga Feed Address setelah itu tekan Activate Feeds.
  •  Setelah Konfirmasi Selesai kita akan diarahkan ke Dashboard Feeds.
  •  Kemudian tekan Menu Publicize lalu pilih Menu Email Subscribetions.
  •  Langkah selanjutnya pilih Menu Radio Button FeedBurner.
  •  Kemudian tekan Activate.
 
Lalu pada Subsciptions Form Code pilih bahas dan Copy Code yang ada di bawahnya, taruh code yang sudah di copy di blog sobat. Caranya: pilih Layout lalu Page Elements, Add a Gadget dan pilih  menu HTML/JavaScript kemudian paste codenya. Penempatan feedburner sendiri disesuaikan dengan template sobat...

Semoga bermanfaat,jika aja yang kurang mengerti silahkan bertanya dengan mengisi kolom komentar di bawah ini. 



Selamat mencoba...

Flow Chart dan Fungsinya

  • Flow Chart adalah diaagram yang menggambarkan susunan logika atau algoritma dari suatu program

  • Simbol-simbol dalam flow chart :





  • Dan ini adalah simbol yang umumnya digunakan,atau dengan kata lain simbol ini sering terpakai :


Cukup sampai disini saja pembahasan tentang flow chat dan kegunaannya,apabila sahabat ada yang kurang mengerti silahkan saja bertanya dengan mengisi kolom komentar dibawah postingan ini.



Semoga Berhasil...

Struktur Dari Bahasa C/C++

Hey teman-teman,kali ini saya akan menjelaskan tentang truktur dalam bahasa C/C++, langsung saja ya..
1. Judul Program itu sifatnya optimal.
  •          Contoh Penulisannya :    
                   1.  /* Judul Program */  
                   2.   // Judul Program

  •           Keterangan :    
              
                    1. Dalam penulisan judul program ini di awali dengan tanda /* sebagai pembuka dan tanda */ sebagai penutupnya, penggunaan tanda ini biasanya digunakan apabila Judul program lebih panjang, atau bisa di katakan apabila Judul Program melebihi 1 Line.
                   2. Penggunaan tanda (double slash) // digunakan apabila Judul Program itu hanya 1 Line.


2. Prototype
merupakan header fungsi-fungsi pada bahasa C/C++

  • Contoh Prototype : 
       /* Judul Program */
       #Include<............>
       #Include<............>


3. Main Program/ Program Utama
tempat statement-statement program. Ditandai dengan "{" untuk Begin/Mulai dan "}" untuk End/Akhir.

  • Contoh Main :
       Main ( )
       ------> Deklarasi Variable Statement-statement..}

Sampai disini saya dapat menerangkan tantang struktur dari bahasa C/C++. Jika ada yang kurang paham,silahkan bertanya dengan mengisinya di kolom komentar..


Salam Sukses...

Antara Programmer Otodidak dan Lulusan Informatika

Apakah anda punya rekan yang bisa pemrograman komputer tapi tidak berlatar belakang informatika/sejenisnya? Saya punya. Mulai dari programmer yang copy paste source code sampai dengan yang mampu bikin class sendiri juga ada. Disisi lain saya juga memiliki teman dengan latar belakang informatika namun kemampuan codingnya sama seperti rekan saya yang otodidak, bahkan ada yang mengaku lulusan informatika namun tidak mampu melakukan coding program.

Saya punya teman, pintar, logic programmingnya oke banget, menguasai lebih dari satu bahasa pemrograman selain itu proses codingnya juga cepat. Kalo disuruh misalnya “Gw butuh program bla.. bla.. bla.., lo bisa buat ga?” dia langsung jawab “Bisa!”. Tapi, giliran disuruh bikin ER Diagram ataupun DFD dia bingung harus mulai darimana.

Lalu timbul pertanyaan saya, kenapa masih ada lulusan informatika bisa dikalahkan oleh orang-orang otodidak dalam pemrograman? sebegitu mudahkah menjadi seorang programmer? apakah hanya dengan mengetahui logika pemrograman dan syntax-nya maka sudah menjadi seorang programmer? Lalu apa yang membedakan programmer lulusan teknik informatika dan yang otodidak?

Berdasarkan pengalaman saya bertemu dengan programmer otodidak, hampir sebagian besar mengerti pemrograman namun tidak diawali dengan belajar teori-teori dasar pemrograman. Biasanya hal itu akan dipelajari sambil berjalan seiring dengan mencoba beberapa baris kode. Sedangkan dalam dunia pendidikan, AFAIK, sebelum coding diharuskan mengerti terlebih dahulu teori-teori dasar seperti misalnya DFD, ER Diagram, bit, Byte dan lain sebagainya, baru nanti akan melangkah ke pemrogramannya.

Jika anda programmer terlepas apapun latar belakangnya tentu pernah mengalami hal-hal seperti dibawah ini :

* Penggunaan beberapa fungsi-fungsi sejenis yang terkadang membingungkan dalam penggunaannya. Seperti misalnya kapan harus menggunakan str_replace dan kapan menggunakan ereg_replace atau kenapa harus strstr daripada preg_match() dalam PHP?
* Jika berhubungan dengan field-field database pernahkah penentuan type field berdasarkan alasan yang jelas? Seperti misalnya kenapa harus bigint daripada int atau langsung comot yang paling besar? *mysql style*
* Kenapa harus ADO daripada DAO untuk melakukan koneksi ke database *Lha, masih pake VB 6.0? :D*

Jujur, untuk hal-hal seperti itu kadang saya harus buka buku lagi, ya maklumlah namanya juga programmer pemula dan otodidak pula *ngeles*.

Berkaca dari contoh kasus diatas, lalu apa yang seharusnya membedakan antara programmer otodidak dan programmer berlatar belakang informatika?

Menurut saya yang memiliki latar belakang informatika harus bisa mengungguli yang otodidak dengan menguasai teori-teori dasar ini. Kemampuan seperti menyusun ER Diagram, DFD, bit, Byte, alokasi memori dan hal-hal lainnya harus bisa dikuasai oleh yang berlatar belakang informatika. Bahkan akan lebih bagus jika programmer berlatar belakang informatika mampu menguasai itu semua namun dapat menjelaskannya dengan bahasa yang mudah dimengerti oleh orang lain. Bukan tidak mungkin programmer otodidak akan mempelajari hal seperti itu mengingat resources pemrograman sangat banyak beredar di internet. Ini tantangan yang akan dialami oleh lulusan informatika khususnya para programmer seperti saya ini.:) 


Perbedaan antara C++ dan Java

Saya baru saja mempelajari dasar-dasar c + + dan tahu beberapa perbedaan dari c + + dan java. Saya ingin pos ini untuk orang lain untuk memiliki petunjuk ketika belajar bahasa baru, baik java ke c + + atau c + + ke java. saya secara pribadi belajar java pertama dan hanya tahu yang dasar-dasar jadi bebas untuk menambahkan pada artikel ini atau hal-hal yang benar.

namespace
c + + menggunakan namespace untuk grup terkait fungsi dan kelas-kelas dan untuk menghindari konflik nama variabel.



namespace name {
 //function and classes here
}

java menggunakan paket ke grup kelas terkait, karena segala sesuatu di java adalah di dalam kelas. Dalam contoh ini yang seperti di dalam namespace namespace


package string.manip.*; //namespace manip inside namespace string
class className {
}



Include

c + + menggunakan file header untuk memasukkan kode yang sudah ditulis sebelumnya dan untuk dapat menggunakan potongan ini kemudian.
#include "mystringmanip.h" 

Walaupun paket java menggunakan namespace, ia juga  bertindak seperti file header.

import java.io.*;


Arguments to main

di c + + argc adalah jumlah argumen dan argv adalah string argumen pada sebuah array

int main(int argc, char* argv[])

di java args secara otomatis objek sebagai array

public static void main(String args[])


Desctructor

in c++  ~classname()

in java  void finalize()


Passing arguments to function

c + + lewat args dengan nilai tetapi masih dapat melewati referensi dengan operator &.
java secara otomatis lulus primitif (int, char, boolean) dengan nilai dan dengan referensi untuk obyek


Pointers

pointer digunakan di c + + untuk mengakses data dalam memori,di java saya pikir tidak ada hal seperti itu meskipun saya tidak yakin.:D


Delete[] / garbage collection

di c + + yang selalu pekerjaan para programmer adalah untuk membebaskan memori yang dialokasikan. di java, pengumpulan sampah dilakukan secara otomatis ketika data di memori sudah tidak ada cara untuk mengaksesnya. meskipun Anda dapat memaksa seorang pengumpulan sampah atau menetapkan nol ke suatu objek.

Terminologies

di c++ foo() disebut function
di java disebut method

dalam java lapangan adalah anggota dari sebuah kelas yang menggambarkan objek.

di c + + foo () dipanggil template di java yang disebut generics.




Semoga Bermanfaat..

Top 10 tips for code porting c/c++

Code portability basically refers to making source code able to compile on different platform without making any changes in source code.
While coding its very important to keep portability in mind.The best way to introduce code portability is while coding.Keeping certain things into account we can achieve code portability with lesser effort, which we will discuss in this post.There are certain tools too which detect portability problems on source code, its a post processing of code and requires extra effort.
Non-portable code introduces problems like maintenance of different versions, reduces readability, reduces understanding of code etc...
Efforts needs to make legacy or old source code portable, can really make you feel lost in this big programming ocean. So, the best policy is to keep portability into account while writing code, it saves lots of time and efforts on rework. Big question now is - "How to write portable code?".Our source code should be compatible with different environment like different processor, different OS, different version of libraries etc... In this post we would focus on basic tips need to be kept in mind while writing code. 

1) Don't assume data type size to be constant across platform, as it may change with platform.
             Many a times programmers makes a common mistake by assuming size of pointer and long same.If in some expression sizeof(long) is used, it may give different result on 32-bit and 64-bit OS version. Like if we talk about Microsoft Visual Studio running on 64-bit OS version the pointer size would be 8 byte and size of long comes out to be 4 byte. Program written with such assumption would give false result or may even get crash.So, one has to be very cautious while using data type size across the platform.

2) Don't use specific system constant.
            System specific constant should not be used as they are not portable, we are some time not aware of them also. Like system constant "NULL" is specific to windows and will give compilation error on other platform. Instead of "NULL" one can use "0". 

3) System file/folder path notation may vary on different platform.
           When working with file path one need to be cautious for example "c:\\TestFile.txt" will work on Windows but give error on Linux.For this one i recommend to use forward slash "c://TestFile.txt" , it would work well on both windows and Linux.

4) Avoid using system specific models/libraries.
         Don't use system specific models/libraries like Event handling model, Threading libraries, File Creation libraries etc.. . As they are not compatible across platform. Write a wrapper around such models and within wrapper use generic portable libraries. For example, Windows even handling model is totally different from Linux. Windows have special mode for handling events, like we may not find timed wait for multiple object on other platform.

5) Always write default statement in switch case.
         Many latest compiler gives compilation error if default is not specified.

6) Always specify return type for functions. 
         Many latest compiler gives compilation error if return type is not specified.

7) Always specify type with static variables.
         Variables declared with static keyword must contain data type with it, some old compiler take int as default type but modern compiler will generate compilation error for it.
8) Always take care of scope of variable.
        Like some compiler support variable scope limited to for() while some compiler dont.
    For example:-

Don't prefer writing code as below (Non-portable code).
        {
           for(int i ; ;)
          {
          //do some thing
           }


           for(int i ; ;)
         {
          //do some thing
          }

        }


         Prefer writing code as below (Portable code)
        {
           for(int i ; ;)
          {
          //do some thing
           }

           for(int j ; ;)
         {
          //do some thing
          }

        }

9) Don't use C++ commenting style in C code.
      Don't use // commenting style in c code, as compile other then microsoft visual studio may generate error for it. Prefer using /* */ commenting style.

10) Take care of include depth for header files and also for file code size.
       Microsoft visual studio compiler generated error like "internal compiler error"  if include depth is too large or file size exceeds certain limit. Always take care of file size and include depth. 

I have tried to cover 10 basic tips for code portability for beginners though there are several other areas too, where we need to focus on advanced portability issues, for e.g. dealing with classes, virtual functions, exception handling, compiler directives, run-time identification. I will cover this topic separately bye for now.
  
Hope you enjoyed this post !

Keep Rocking
-Tajendra
http://tajendrasengar.blogspot.com/2010/03/how-to-achieve-code-portability-basic.html

IOstream Library




Standard Input / Output Streams Library


The iostream library is an object-oriented library that provides input and output functionality using streams.

A stream is an abstraction that represents a device on which input and ouput operations are performed. A stream can basically be represented as a source or destination of characters of indefinite length.

click on an element for detailed 
information


Streams are generally associated to a physical source or destination of characters, like a disk file, the keyboard, or the console, so the characters gotten or written to/from our abstraction called stream are physically input/output to the physical device. For example, file streams are C++ objects to manipulate and interact with files; Once a file stream is used to open a file, any input or output operation performed on that stream is physically reflected in the file.

To operate with streams, C++ provides the standard iostream library, which contains the following elements:

Basic class templates
The base of the iostream library is the hierarchy of class templates. The class templates provide most of the functionality of the library in a type-independent fashion.
This is a set of class templates, each one having two template parameters: the char type (charT) parameter, that determines the type of elements that are going to be manipulated and the traits parameter, that provides additional characteristics specific for a particular type of elements.
The class templates in this class hierarchy have the same name as their char-type instantiations but with the prefix basic_. For example, the class template which istream is instantiated from is called basic_istream, the one from which fstream is is called basic_fstream, and so on... The only exception is ios_base, which is by itself type-independent, and therefore is not based on a template, but is a regular class.
Class template instantiations
The library incorporates two standard sets of instantiations of the entire iostream class template hierarchy: one is narrow-oriented, to manipulate elements of type char and another one, wide-oriented, to manipulate elements of type wchar_t.
The narrow-oriented (char type) instantiation is probably the better known part of the iostream library. Classes like ios, istream and ofstream are narrow-oriented. The diagram on top of this page shows the names and relationships of narrow-oriented classes.
The classes of the wide-oriented (wchar_t) instatiation follow the same naming conventions as the narrow-oriented instantiation but with the name of each class and object prefixed with a w character, forming wios, wistream and wofstream, as an example.
Standard objects
As part of the iostream library, the header file declares certain objects that are used to perform input and output operations on the standard input and output.
They are divided in two sets: narrow-oriented objects, which are the popular cin, cout, cerr and clog and their wide-oriented counterparts, declared as wcin, wcout, wcerr and wclog.
Types
The iostream classes barely use fundamental types on their member's prototypes. They generally use defined types that depend on the traits used in their instantiation. For the default char and wchar_t instantiations, types streampos, streamoff and streamsize are used to represent positions, offsets and sizes, respectively.
Manipulators
Manipulators are global functions designed to be used together with insertion (<<) and extraction (>>) operators performed on iostream stream objects. They generally modify properties and formatting settings of the streams. endl, hex and scientific are some examples of manipulators.


Organization

The library and its hierarchy of classes is split in different files:
  • , , , and aren't usually included directly in most C++ programs. They describe the base classes of the hierarchy and are automatically included by other header files of the library that contain derived classes.
  • declares the objects used to communicate through the standard input and output (including cin and cout).
  • defines the file stream classes (like the template basic_ifstream or the class ofstream) as well as the internal buffer objects used with these (basic_filebuf). These classes are used to manipulate files using streams.
  • : The classes defined in this file are used to manipulate string objects as if they were streams.
  • declares some standard manipulators with parameters to be used with extraction and insertion operators to modify internal flags and formatting options.


Compatibility notes

The names, prototypes and examples included in this reference for the iostream classes mostly describe and use the char instantiations of the class templates instead of the templates themselves, even though these classes are only one of their possible instantiations. We believe this provides a better readability and is arguably as easy to obtain the names and prototypes of the basic template from the char instantiation as the opposite.

Elements of the iostream library (char instantitation)

Classes:


Objects:


Types:


Manipulators:

Reference: cplusplus.com

Operators

Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose, C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code shorter and more international, since it relies less on English words, but requires a little of learning effort in the beginning.

You do not have to memorize all the content of this page. Most details are only provided to serve as a later reference in case you need it.

Assignment (=)

The assignment operator assigns a value to a variable.

a = 5;
 
This statement assigns the integer value 5 to the variable a. The part at the left of the assignment operator (=) is known as the lvalue (left value) and the right one as the rvalue (right value).
The lvalue has to be a variable whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these. The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from right to left, and never the other way:

a = b;


This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was stored until this moment in a is not considered at all in this operation, and in fact that value is lost.

Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore a later change of b will not affect the new value of a.

For example, let us have a look at the following code - I have included the evolution of the content stored in the variables as comments:
// assignment operator

#include <iostream>
using namespace std;

int main ()
{
  int a, b;         // a:?,  b:?
  a = 10;           // a:10, b:?
  b = 4;            // a:10, b:4
  a = b;            // a:4,  b:4
  b = 7;            // a:4,  b:7

  cout << "a:";
  cout << a;
  cout << " b:";
  cout << b;

  return 0;
}

This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-to-left rule).

A property that C++ has over other programming languages is that the assignment operation can be used as the rvalue (or part of an rvalue) for another assignment operation. For example:

a = 2 + (b = 5);


is equivalent to:


b = 5;
a = 2 + b;


that means: first assign 5 to variable b and then assign to a the value 2 plus the result of the previous assignment of b (i.e. 5), leaving a with a final value of 7.

The following expression is also valid in C++: 
a = b = c = 5;


It assigns 5 to the all the three variables: a, b and c.

Arithmetic operators ( +, -, *, /, % )

The five arithmetical operations supported by the C++ language are:  



+ addition
- subtraction
* multiplication
/ division
% modulo


Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write:

a = 11 % 3;


the variable a will contain the value 2, since 2 is the remainder from dividing 11 between 3.

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)


When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:



expression is equivalent to
a - = 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1 price = price * (units + 1);


and the same for all other operators. For example:
// compound assignment operators

#include <iostream>
using namespace std;

int main ()
{
  int a, b=3;
  a = b;
  a+=2;             // equivalent to a=a+2
  cout << a;
  return 0;
}

Increase and decrease (++, --)

Shortening even more some expressions, the increase operator (++) and the decrease operator (--) increase or reduce by one the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:



c++;
c+=1;
c=c+1;


are all equivalent in its functionality: the three of them increase by one the value of c.

In the early C compilers, the three previous expressions probably produced different executable code depending on which one was used. Nowadays, this type of code optimization is generally done automatically by the compiler, thus the three expressions should produce exactly the same executable code.

A characteristic of this operator is that it can be used both as a prefix and as a suffix. That means that it can be written either before the variable identifier (++a) or after it (a++). Although in simple expressions like a++ or ++a both have exactly the same meaning, in other expressions in which the result of the increase or decrease operation is evaluated as a value in an outer expression they may have an important difference in their meaning: In the case that the increase operator is used as a prefix (++a) the value is increased before the result of the expression is evaluated and therefore the increased value is considered in the outer expression; in case that it is used as a suffix (a++) the value stored in a is increased after being evaluated and therefore the value stored before the increase operation is evaluated in the outer expression. Notice the difference:



Example 1 Example 2
B=3; B=3;
A=++B; A=B++;
// A contains 4, B contains 4 // A contains 3, B contains 4


In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.

Relational and equality operators ( ==, !=, >, <, >=, <= )


In order to evaluate a comparison between two expressions we can use the relational and equality operators. The result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result.

We may want to compare two expressions, for example, to know if they are equal or if one is greater than the other is. Here is a list of the relational and equality operators that can be used in C++: 


==      Equal to
!=      Not equal to
>          Greater than
<     Less than


Here there are some examples:

1
2
3
4
5
(7 == 5)     // evaluates to false.
(5 > 4)      // evaluates to true.
(3 != 2)     // evaluates to true.
(6 >= 6)     // evaluates to true.
(5 < 5)      // evaluates to false. 


Of course, instead of using only numeric constants, we can use any valid expression, including variables. Suppose that a=2, b=3 and c=6,

1
2
3
4
(a == 5)     // evaluates to false since a is not equal to 5.
(a*b >= c)   // evaluates to true since (2*3 >= 6) is true. 
(b+4 > a*c)  // evaluates to false since (3+4 > 2*6) is false. 
((b=2) == a) // evaluates to true.  


Be careful! The operator = (one equal sign) is not the same as the operator == (two equal signs), the first one is an assignment operator (assigns the value at its right to the variable at its left) and the other one (==) is the equality operator that compares whether both expressions in the two sides of it are equal to each other. Thus, in the last expression ((b=2) == a), we first assigned the value 2 to b and then we compared it to a, that also stores the value 2, so the result of the operation is true.

Logical operators ( !, &&, || )


The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:

1
2
3
4
!(5 == 5)    // evaluates to false because the expression at its right (5 == 5) is true. 
!(6 <= 4)    // evaluates to true because (6 <= 4) would be false. 
!true        // evaluates to false
!false       // evaluates to true.  


The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a && b:

&& OPERATOR
ab  a && b
true  true   true
true  false   false
false  true   false
false  false     false


The operator || corresponds with Boolean logical operation OR. This operation results true if either one of its two operands is true, thus being false only when both operands are false themselves. Here are the possible results of a || b:

|| OPERATOR
aba || b
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse


For example:

1
2
( (5 == 5) && (3 > 6) )  // evaluates to false ( true && false ).
( (5 == 5) || (3 > 6) )  // evaluates to true ( true || false ). 


Conditional operator ( ? )


The conditional operator evaluates an expression returning a value if that expression is true and a different one if the expression is evaluated as false. Its format is:


condition ? result1 : result2


If condition is true the expression will return result1, if it is not it will return result2.

1
2
3
4
7==5 ? 4 : 3     // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3   // returns 4, since 7 is equal to 5+2.
5>3 ? a : b      // returns the value of a, since 5 is greater than 3.
a>b ? a : b      // returns whichever is greater, a or b.  

// conditional operator

#include <iostream>
using namespace std;

int main ()
{
  int a,b,c;

  a=2;
  b=7;
  c = (a>b) ? a : b;

  cout << c;

  return 0;
}


In this example a was 2 and b was 7, so the expression being evaluated (a>b) was not true, thus the first value specified after the question mark was discarded in favor of the second value (the one after the colon) which was b, with a value of 7.

Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.

For example, the following code:

a = (b=3, b+2);


Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.

Bitwise Operators ( &, |, ^, ~, <<, >> )


Bitwise operators modify variables considering the bit patterns that represent the values they store.

operatorasm equivalentdescription
&ANDBitwise AND
|ORBitwise Inclusive OR
^XORBitwise Exclusive OR
~NOTUnary complement (bit inversion)
<<SHLShift Left
>>SHRShift Right


Explicit type casting operator

Type casting operators allow you to convert a datum of a given type to another. There are several ways to do this in C++. The simplest one, which has been inherited from the C language, is to precede the expression to be converted by the new type enclosed between parentheses (()):

1
2
3
int i;
float f = 3.14;
i = (int) f;


The previous code converts the float number 3.14 to an integer value (3), the remainder is lost. Here, the typecasting operator was (int). Another way to do the same thing in C++ is using the functional notation: preceding the expression to be converted by the type and enclosing the expression between parentheses:

i = int ( f );


Both ways of type casting are valid in C++.

sizeof()

This operator accepts one parameter, which can be either a type or a variable itself and returns the size in bytes of that type or object:

a = sizeof (char);


This will assign the value 1 to a because char is a one-byte long type.
The value returned by sizeof is a constant, so it is always determined before program execution.

Other operators

Later in these tutorials, we will see a few more operators, like the ones referring to pointers or the specifics for object-oriented programming. Each one is treated in its respective section.

Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand is evaluated first and which later. For example, in this expression:

a = 5 + 7 % 2


we may doubt if it really means:

1
2
a = 5 + (7 % 2)    // with a result of 6, or
a = (5 + 7) % 2    // with a result of 0 


The correct answer is the first of the two expressions, with a result of 6. There is an established order with the priority of each operator, and not only the arithmetic ones (those whose preference come from mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority order is as follows:

LevelOperatorDescriptionGrouping
1::scopeLeft-to-right
2() [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeidpostfixLeft-to-right
3++ -- ~ ! sizeof new deleteunary (prefix)Right-to-left
* &indirection and reference (pointers)
+ -unary sign operator
4(type)type castingRight-to-left
5.* ->*pointer-to-memberLeft-to-right
6* / %multiplicativeLeft-to-right
7+ -additiveLeft-to-right
8<< >>shiftLeft-to-right
9< > <= >=relationalLeft-to-right
10== !=equalityLeft-to-right
11&bitwise ANDLeft-to-right
12^bitwise XORLeft-to-right
13|bitwise ORLeft-to-right
14&&logical ANDLeft-to-right
15||logical ORLeft-to-right
16?:conditionalRight-to-left
17= *= /= %= += -= >>= <<= &= ^= |=assignmentRight-to-left
18,commaLeft-to-right


Grouping defines the precedence order in which operators are evaluated in the case that there are several operators of the same level in an expression.

All these precedence levels for operators can be manipulated or become more legible by removing possible ambiguities using parentheses signs ( and ), as in this example:

a = 5 + 7 % 2;


might be written either as:

a = 5 + (7 % 2);

or
a = (5 + 7) % 2;


depending on the operation that we want to perform.

So if you want to write complicated expressions and you are not completely sure of the precedence levels, always include parentheses. It will also become a code easier to read.
Published by Juan Soulie

Constants


 Constants are expressions with a fixed value.

Literals

Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote:


a = 5;
 
the 5 in this piece of code was a literal constant.
Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.

Integer Numerals

1776
707
-273
 
They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. There is no doubt that it is a constant: whenever we write 1776 in a program,we will be referring to the value 1776.

In addition to decimal numbers (those that all of us are used to use every day) C++ allows the use as literal constants of octal numbers (base 8) and hexadecimal numbers (base 16). If we want to express an octal number we have to precede it with a 0 (a zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x (zero, x). For example, the following literal constants are all equivalent to each other:
75         // decimal
0113       // octal
0x4b       // hexadecimal
 All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively.

Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l:
75         // int
75u        // unsigned int
75l        // long
75ul       // unsigned long
 In both cases, the suffix can be specified using either upper or lowercase letters.

Floating Point Numbers

They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character:

3.14159    // 3.14159
6.02e23    // 6.02 x 10^23
1.6e-19    // 1.6 x 10^-19
3.0        // 3.0 
 
 
These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal.

The default type for floating point literals is double. If you explicitly want to express a float or a long double numerical literal, you can use the f or l suffixes respectively:
3.14159L   // long double
6.02e23f   // float
 
Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.

Character and string literals

There also exist non-numerical constants, like:
 
'z'
'p'
"Hello world"
"How do you do?" 
 
The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").

When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions:


x
'x'

x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes:



\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ back slash (\)

For example:

'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree" 

Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).

String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line.

"string expressed in \
two lines" 

You can also concatenate several string constants separating them by one or several blank spaces, tabulators, newline or any other valid blank character:

"this forms" "a single" "string" "of characters"

Finally, if we want the string literal to be explicitly made of wide characters (wchar_t type), instead of narrow characters (char type), we can precede the constant with the L prefix:

L"This is a wide character string" 

Wide characters are used mainly to represent non-English or exotic character sets.

Boolean literals

There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false.

Defined constants (#define)

You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is:
#define identifier value

For example:

#define PI 3.14159
#define NEWLINE '\n' 

This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example:

// defined constants: calculate circumference

#include 
using namespace std;

#define PI 3.14159
#define NEWLINE '\n'

int main ()
{
  double r=5.0;               // radius
  double circle;

  circle = 2 * PI * r;
  cout << circle;
  cout << NEWLINE;

  return 0;
}

In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (3.14159 and '\n' respectively).

The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences of the identifier within the body of the program that the preprocessor replaces.


Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would do with a variable: 

const int pathwidth = 100;
const char tabulator = '\t';

Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.

Published by Juan Soulie