Yapısal Programlamada C ve C++ Arasındaki Farklar

Mithat Konar – Yapısal Programlama
9 Mayıs 2004

Giriş

For new application development, C++ long ago replaced C as the dominant programming language. This is a good thing. C was never intended to be and never actually was a proper high-level language. Some even refer to it as a “high-level assembly language”. Whether you agree with that characterization or not, it must be confessed that C is a cumbersome beast.

C++, even for procedural programming, offers a number of advantages over C including stronger type checking, improved I/O, and references. Many of the low-level features that confuse new programmers — including the relationships between pointers and arrays and pointers and strings — are still present. However, C++ still represents a significant step forward.

But…

In spite of the fact that C++ has almost completely replaced C as the language of choice for new desktop application development, we still find C in our midst. Reasons include:

(1) There is a lot of legacy code that is written in C.
(2) Most microcontroller development environments support only C for high-level language development.
(3) C-front C++ compilers are still with us—meaning that for debugging and optimization you may actually have to dig into the intermediate C code.

C++ was conceived of as a language to support object-oriented programming. Therefore there are many programming structures, etc. that exist in C++ that have absolutely no analog in C. However, there exist some important differences between the two languages even at the structured programming level. Below is a summary of the most significant of these differences.

The smaller details

  • void main() is permitted
  • For standard I/0, #include <stdio.h> is used instead of #include <iostream>
  • Within a block, variable declarations must be made before any executable statements
  • // comments do not exist in C, only /* comment */ format exists
  • Constants are typically defined using #define PI = 3.14159 macros
  • Casting syntax: x = (double)myInt/10;
  • References do not exists in C. Call-by-value must be implemented using pointers.

The bigger details

Standard I/O

Standard output

For standard output C uses the printf() function instead of the cout object. The protoype is:
int printf(const char *format, arg1, arg2, arg3, ……);

The basic idea is that you pass a format string to printf along with any variables whose values you want to print. Examples:

printf(“Hello world.”); /* prints “Hello world.” */

printf(“Hello world.\n”); /* prints “Hello world.” and moves cursor to
                             a newline */

int luckyNumber = 5;

printf(“My lucky number is %d\n”, luckyNumber);    /* The “%d” specifies
                                                      that an integer value
                                                      will be output. */

float radius = 2.0;

printf(“The radius of the circle is %f\n”, radius);  /* %f specifies that a float will
                                                        be output. */

printf(“The area of a circle with radius %f is %f\n”, radius, 3.14*radius*radius);

char myName[15] = “John”;

printf(“My name is %s\n”, myName);    /* The %s specifies that a
                                         character string will be output. */

char initial = ‘J’;

printf(“My first initial is %c\n”, initial);   /* The %c specifies that
                                                  a character will be
                                                  output. */

printf(“Hello %s or should I say %c\n”, myName, initial); /* Multiple arguments
                                           of different types may be output. */

format specifier        associated type

%d                              int

%f                               float or double

%e                              float or double, output in scientific notation.

%c                              character

%s                               character string

#include <stdio.h>

int main()

{

    int luckyNumber = 5;

    float radius = 2.0;

    char myName[15] = “John”;

    char initial = ‘J’;

    printf(“Hello World\n”);    /* The format string contains only ordinary

                    characters. Ordinary characters are output unmodified.

                    A character string in C is of type “char *”. */

    printf(“My lucky number is %d\n”, luckyNumber);    /* The “%d” specifies

                   that an integer value will be output. */

    printf(“My name is %s\n”,myName);    /* The %s specifies that a character

                   string will be output. */

    printf(“My first initial is %c\n”,initial);    /* The %c specifies that a

                   character will be output. */

    printf(“The area of a circle with radius %f is %f\n”, radius, 3.14*radius*radius);

                   /* %f specifies that a float will be output. */

    printf(“Hello %s or should I say %c\n”,myName,initial);

                   /* Multiple arguments of different types may be output. */

    return(0);

}

printf() returns an integer value equal to the number of characters output, or some negative number if an error occurred.

Other functions and macros are available in stdio.h for standard output, but printf() is the most common.

Standard input

For standard input C uses the scanf() function instead of the cin object. The prototype is:

int scanf(const char *format, arg1, arg2, ….);

scanf() uses the same format specifiers as printf().

Examples:

int number;;

scanf(“%d”,&number); /* gets an int from standard input and writes it to number */ 

float radius;

scanf(“%f”,&radius); /* gets a float from standard input and writes it to radius */ 

char yourName[15];

scanf(“%s”,yourName); /* gets a string form standard input and writes it to yourName */

                      /* note that & does not precede string names! */

#include <stdio.h>

int main()

{

    float radius;

    char yourName[15];

    int number;

    printf(“Enter the radius of circle: “);

    scanf(“%f”,&radius);   /* & is the “address of” operator.

                    The address of radius is passed into scanf. Passing

                    the address of a variable is equivalent to passing

                    a pointer containing the address of the variable. */

    printf(“A circle of radius %f has area %f\n”,radius,3.14*radius*radius);

    printf(“Enter a number from 1 to 1000: “);

    scanf(“%d”,&number);

                    /* The address of number is passed to scanf */

    printf(“Your number is %d\n”,number);

    printf(“Enter your name: “);

    scanf(“%s”,yourName);    /* yourName is a character array.

                    yourName[0] specifies the first element of the array.

                    &yourName[0] specifies the address of the first element

                    of the array. In C, an array name by itself is shorthand

                    for the address of the first element. So, yourName is

                    equivalent to &yourName[0], which is what must be

                    passed into scanf. This will be made clearer in the

                    lesson covering arrays. */

    printf(“Hello %s\n”,yourName);

    return(0);

}

scanf() returns an integer, either the number of values read in, or EOF if an end of file is reached. EOF is a special termination character, specified in stdio.h, which designates the end of a file. If no values are successfully read, scanf() returns zero.

Other functions and macros are available in stdio.h for standard input, but scanf() is the most common.

File I/O

C uses FILE pointers to facilitate file input and output. FILE pointers are used to open and close files as well as to provide references to files when writing and reading. Writing to and reading from files are accomplished using the fprintf() and fscanf() functions. fprintf() and fscanf() operate in a ways that are nearly identical to the standard I/0 functions printf() and scanf().

Examples:

FILE *ifp, *ofp; /*create two FILE pointers */

ifp = fopen(“inputFile.txt”,”r”);  /* opens the file “inputFile.txt” for reading from */

ofp = fopen(“outputFile.txt”,”w”);  /* opens the file “outputFile.txt” for writing to */

fopen() will open a file specified by the first argument subject to the mode specified by the second argument. Note that both arguments are strings. The permitted open modes are:

Mode    Use

r             open for reading

w           open or create for writing. Truncate (discard) any previous contents.

a            open or create for writing. Append (write after) any previous contents.

r+           open file for update (reading and writing).

w+         open or create file for update. Truncate (discard) any previous data.

a+          open or create file for update. Append (write after) any previous data.

Once a file is open, it can be read from or written to:

/* Reading data */

fscanf(ifp,”%s”, name);  /* reads first data item as a string and writes it to variable name
                          */

fscanf(ifp,”%d”, &idNum); /* reads second data item as an integer and writes it to idNum */

fscanf(ifp,”%s %d”, name, &idNum); /* reads both data items in one statement */

/* Writing data */

fprintf(ofp,”%d %s\n”,idNum, name); /* writes idNum and name to file */

After you are finished reading from or writing to a file, it should be closed.

fclose(ifp);

fclose(ofp);

After a file is closed, the FILE pointer can be used to open another file.

Complete program:

#include <stdio.h>

int main()

{

    char ifilename[] = “inFile.txt”;

    char ofilename[] = “outFile.txt”;

    char name[30];

    int idNum;

    FILE *ofp, *ifp;

    /* Open file for input */

    ifp = fopen(ifilename,”r”);

    /* Read data */

    fscanf(ifp,”%s %d”,name,&idNum);

    /* Open file for output */

    ofp = fopen(ofilename,”w”);

    /* Write out data */

    fprintf(ofp,”%d %s\n”,idNum, name);

    /* Close Files */

    fclose(ifp);

    fclose(ofp);

    return 0;

}

Other functions and macros are available for writing to and reading from files, but fprintf() and fscanf() are the most common.

Note: Some of the content and most of the examples in this document are based on the tutorial found at http://cplus.about.com/library/blctut.htm by John Kopp.