Sie sind auf Seite 1von 17

Q1. What are the features of C language?

Ans.
1. C is highly portable, i.e., C programs written for one computer can be run on another with little or no
modification.
2. C language is well suited for structured programming, which requires user to think of any problem
in terms of function modules or blocks. A proper collection of these modules would make a complete
program.
3…

Q2. What will happen if we use more than one main function?
Ans. The compiler cannot understand which one marks the beginning of the program.

The empty pair of parentheses immediately following main indicates that the function main has no
arguments (or parameters).
All the statements between those curly braces form the function body. The function body contains a set
of instructions to perform a given task.
The lines beginning with /* and ending with */ are known as comment lines. These are used in a program
to enhance its readability and understanding. Comment lines are not executable statements and thereore
anything between /* and */ is ignored by the compiler. Comment lines cannot be nested in C.
/* = = = /* = = = = */ = = = */
printf is a standard C function for printing output. Predefined means that it is a function that has already
been written and compiled, and linked together with our program at the time of linking.
Every statement in C should end with a semicolon (;) mark.

\n – escape sequences, new line character


C does make a distinction between uppercase and lowercase letters. Printf and printf are not same.

The main Function: Different forms of main function


main(), int main(), void main(), main(void), void main(void), int main(void)
Emplty pair of parentheses indicates that the function has no arguments. Keyword void means that the
function does not return any information to the operating system.

Sample program 2: Adding two numbers, till decimal places


/* Program Addition*/
/*Written by xyz*/
#include<stdio.h>
int main()
{
Int number;
Float amount;
Number = 100;
Amount = 30.75+75.35;
Printf(“%d\n”,number);
Printf(“%5.2f”,amount)’
Return 0;
}
ANS: 100, 106.10
The variables must be declared before they are used.
All declaration statements must end with a semicolon.
Words int, float are keywords, can’t use them as variable names.
Number =100 is an assignment statement. Every assignment statement must have a semicolon at the
end.
The newline character \n causes the next output to appear on a new line.
The format specification %5.2f tells the compiler that the output must be in floating point.
The #define directive is a pre-processor compiler directive and not a statement. Therefore #define lines
should not end with a semicolon. Symbolic constants are generally written in uppercase so that they are
easily distinguished from lowercase variable names. #define instructions are usually placed at the
beginning before the main() function. Symbolic constants are not declared at the declaration section.

Floating point variables are declared in one statement.


Process of compiling and running a C program done already.

Errors in C/C++
Error is an illegal operation performed by the user which results in abnormal working of the program.
Programming errors often remain undetected until the program is compiled or executed. Some of the
errors inhibit the program from getting compiled or executed. Thus errors should be removed before
compiling and executing.
The most common errors can be broadly classified as follows.
Type of errors
1. Syntax errors: In computer science, a syntax error is an error in the syntax of a
sequence of characters or tokens that is intended to be written in a particular
programming language. For compiled languages, syntax errors are detected at
compile-time. Errors that occur when you violate the rules of writing C/C++ syntax are known
as syntax errors. This compiler error indicates something that must be fixed before the code can
be compiled. All these errors are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:

 Missing Parenthesis (})


 Printing the value of variable without declaring it
 Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
int x = 10;
int y = 15;

printf("%d", (x, y)) // semicolon missed


}
 Run on IDE
 Error:

 error: expected ';' before '}' token

 Syntax of a basic construct is written wrong. For example : while loop


// C program to illustrate
// syntax error
#include<stdio.h>
int main(void)
{
// while() cannot contain "." as an argument.
while(.)
{
printf("hello");
}
return 0;
}
 Run on IDE
 Error:

 error: expected expression before '.' token

 while(.)

 In the given example, the syntax of while loop is incorrect. This causes a syntax error.
2. Run-time Errors : Errors which occur during program execution(run-time) after successful
compilation are called run-time errors. One of the most common run-time error is division by
zero also known as Division error. These types of error are hard to find as the compiler doesn’t
point to the line at which the error occurs.
For more understanding run the example given below.
// C program to illustrate
// run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;

// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;

printf("resut = %d", div);


}
3. Run on IDE
4. Error:
5.

6. warning: division by zero [-Wdiv-by-zero]


7. div = n/0;

8. In the given example, there is Division by zero error. This is an example of run-time error i.e
errors occurring while running the program.
9. Linker Errors: These error occurs when after compilation we link the different object files with
main’s object using Ctrl+F9 key(RUN). These are errors generated when the executable of the
program cannot be generated. This may be due to wrong function prototyping, incorrect header
files. One of the most common linker error is writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>

void Main() // Here Main() should be main()


{
int a = 10;
printf("%d", a);
}
10. Run on IDE
11. Error:

12. (.text+0x20): undefined reference to `main'

13. Logical Errors : On compilation and execution of a program, desired output is not obtained when
certain input values are given. These types of errors which provide incorrect output but appears
to be error free are called logical errors. These are one of the most common errors done by
beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
// C program to illustrate
// logical error
int main()
{
int i = 0;

// logical error : a semicolon after loop


for(i = 0; i < 3; i++);
{
printf("loop ");
continue;
}
getchar();
return 0;
}
14. Run on IDE
15. No output
16. Semantic errors : This error occurs when the statements written in the program are not
meaningful to the compiler.
// C program to illustrate
// semantic error
void main()
{
int a, b, c;
a + b = c; //semantic error
}
17. Run on IDE
18. Error

19. error: lvalue required as left operand of assignment


20. a + b = c; //semantic error

Interesting Facts about Macros and Preprocessors in C


In a C program, all lines that start with # are processed by preprocessor which is a special
program invoked by the compiler. In a very basic term, preprocessor takes a C program and
produces another C program without any #.
Following are some interesting facts about preprocessors in C.
1) When we use include directive, the contents of included header file (after preprocessing)
are copied to the current file.
Angular brackets < and > instruct the preprocessor to look in the standard folder where all
header files are held. Double quotes “ and “ instruct the preprocessor to look into the current
folder and if the file is not present in current folder, then in standard folder of all header files.
2) When we use define for a constant, the preprocessor produces a C program where the
defined constant is searched and matching tokens are replaced with the given expression. For
example in the following program max is defined as 100.
#include<stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}
// Output: max is 100
// Note that the max inside "" is not replaced
Run on IDE
3) The macros can take function like arguments, the arguments are not checked for data type.
For example, the following macro INCREMENT(x) can be used for x of any data type.
#include <stdio.h>
#define INCREMENT(x) ++x
int main()
{
char *ptr = "GeeksQuiz";
int x = 10;
printf("%s ", INCREMENT(ptr));
printf("%d", INCREMENT(x));
return 0;
}
// Output: eeksQuiz 11
Run on IDE
4) The macro arguments are not evaluated before macro expansion. For example consider
the following program
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
// The macro is expended as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
// Output: 16
Run on IDE
5) The tokens passed to macros can be concatenated using operator ## called Token-Pasting
operator.

#include <stdio.h>
#define merge(a, b) a##b
int main()
{
printf("%d ", merge(12, 34));
}
// Output: 1234
Run on IDE
6) A token passed to macro can be converted to a string literal by using # before it.
#include <stdio.h>
#define get(a) #a
int main()
{
// GeeksQuiz is changed to "GeeksQuiz"
printf("%s", get(GeeksQuiz));
}
// Output: GeeksQuiz
Run on IDE
7) The macros can be written in multiple lines using ‘\’. The last line doesn’t need to have ‘\’.
#include <stdio.h>
#define PRINT(i, limit) while (i < limit) \
{ \
printf("GeeksQuiz "); \
i++; \
}
int main()
{
int i = 0;
PRINT(i, 3);
return 0;
}
// Output: GeeksQuiz GeeksQuiz GeeksQuiz
Run on IDE
8) The macros with arguments should be avoided as they cause problems sometimes. And
Inline functions should be preferred as there is type checking parameter evaluation in inline
functions. From C99 onward, inline functions are supported by C language also.
For example consider the following program. From first look the output seems to be 1, but it
produces 36 as output.
#define square(x) x*x
int main()
{
int x = 36/square(6); // Expended as 36/6*6
printf("%d", x);
return 0;
}
// Output: 36
Run on IDE
If we use inline functions, we get the expected output. Also the program given in point 4 above
can be corrected using inline functions.
inline int square(int x) { return x*x; }
int main()
{
int x = 36/square(6);
printf("%d", x);
return 0;
}
// Output: 1
Run on IDE
9) Preprocessors also support if-else directives which are typically used for conditional
compilation.
int main()
{
#if VERBOSE >= 2
printf("Trace Message");
#endif
}
Run on IDE
10) A header file may be included more than one time directly or indirectly, this leads to
problems of redeclaration of same variables/functions. To avoid this problem, directives
like defined, ifdef and ifndef are used.
11) There are some standard macros which can be used to print program file (__FILE__),
Date of compilation (__DATE__), Time of compilation (__TIME__) and Line Number in C code
(__LINE__)
#include <stdio.h>

int main()
{
printf("Current File :%s\n", __FILE__ );
printf("Current Date :%s\n", __DATE__ );
printf("Current Time :%s\n", __TIME__ );
printf("Line Number :%d\n", __LINE__ );
return 0;
}

/* Output:
Current File :C:\Users\GfG\Downloads\deleteBST.c
Current Date :Feb 15 2014
Current Time :07:04:25
Line Number :8 */

Compiling a C program:- Behind the Scenes


C is a high level language and it needs a compiler to convert it into an executable code so
that the program can be run on our machine.
What goes inside the compilation process?
Compiler converts a C program into an executable. There are four phases for a C
program to become an executable:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
Pre-processing
This is the first phase through which source code is passed. This phase include:
 Removal of Comments
 Expansion of Macros
 Expansion of the included files.
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i:
using $vi filename.i
Analysis:
 printf contains now a + b rather than add(a, b) that’s because macros have expanded.
 Comments are stripped off.
 #include<stdio.h> is missing instead we see lots of code. So header files has been expanded
and included in our source file.
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output
file filename.s. This file is in assembly level instructions. Let’s see through this file
using $vi filename.s
Assembly
In this phase the filename.s is taken as input and turned into filename.o by assembler.
This file contain machine level instructions. At this phase, only existing code is
converted into machine language, the function calls like printf() are not resolved. Let’s
view this file using $vi filename.o
Linking
This is the final phase in which all the linking of function calls with their definitions are
done. Linker knows where all these functions are implemented. Linker does some
extra work also, it adds some extra code to our program which is required when the
program starts and ends. For example, there is a code which is required for setting up
the environment like passing command line arguments. This task can be easily verified
by using $size filename.o and $size filename. Through these commands, we know
that how output file increases from an object file to an executable file. This is because
of the extra code that linker adds with our program.

Benefits of C language over other programming


languages
C is a middle level programming language developed by Dennis Ritchie during the early 1970s while
working at AT&T Bell Labs in USA. The objective of its development was in the context of the re-design
of the UNIX operating system to enable it to be used on multiple computers.
Earlier the language B was now used for improving the UNIX system. Being a high level language, B
allowed much faster production of code than in assembly language. Still, B suffered from drawbacks as
it did not understand data-types and did not provide the use of “structures”.
These drawbacks became the driving force for Ritchie for development of a new programming language
called C. He kept most of language B’s syntax and added data-types and many other required changes.
Eventually C was developed during 1971-73, containing both high-level functionality and the detailed
features required to program an operating system. Hence, many of the UNIX components including
UNIX kernel itself were eventually rewritten in C.

Benefits of C language
1. As a middle level language, C combines the features of both high level and low level languages.
It can be used for low-level programming, such as scripting for drivers and kernels and it also
supports functions of high level programming languages, such as scripting for software
applications etc.
2. C is a structured programming language which allows a complex program to be broken into
simpler programs called functions. It also allows free movement of data across these functions.
3. Various features of C including direct access to machine level hardware APIs, presence of C
compilers, deterministic resource use and dynamic memory allocation make C language an
optimum choice for scripting applications and drivers of embedded systems.
4. C language is case-sensitive which means lowercase and uppercase letters are treated
differently.
5. C is highly portable and is used for scripting system applications which form a major part of
Windows, UNIX and Linux operating system.
6. C is a general purpose programming language and can efficiently work on enterprise applications,
games, graphics, and applications requiring calculations etc.
7. C language has a rich library which provides a number of built-in functions. It also offers dynamic
memory allocation.
8. C implements algorithms and data structures swiftly, facilitating faster computations in programs.
This has enabled the use of C in applications requiring higher degrees of calculations
like MATLAB and Mathematica.

Escape Sequences in C
In C programming language, there are 256 numbers of characters in character set. The entire character
set is divided into 2 parts i.e. the ASCII characters set and the extended ASCII characters set. But apart
from that, some other characters are also there which are not the part of any characters set, known as
ESCAPE characters.

List of Escape Sequences


\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\ooo octal number

\xhh hexadecimal number

\0 Null

Some coding examples of escape characters

// C program to illustrate
// \a escape sequence

#include <stdio.h>

int main(void)

printf("My mobile number "

"is 7\a8\a7\a3\a9\a2\a3\a4\a0\a8\a");

return (0);

Run on IDE
Output:
My mobile number is 7873923408.

// C program to illustrate

// \b escape sequence

#include <stdio.h>

int main(void)

// \b - backspace character transfers

// the cursor one character back with

// or without deleting on different

// compilers.

printf("Hello Geeks\b\b\b\bF");

return (0);

Run on IDE
Output:

The output is dependent upon compiler.

// C program to illustrate

// \n escape sequence

#include <stdio.h>

int main(void)

// Here we are using \n, which

// is a new line character.

printf("Hello\n");

printf("GeeksforGeeks");

return (0);

Run on IDE
Output:

Hello

GeeksforGeeks

// C program to illustrate
// \t escape sequence

#include <stdio.h>

int

main(void)

// Here we are using \t, which is

// a horizontal tab character.

// It will provide a tab space

// between two words.

printf("Hello \t GFG");

return (0);

Run on IDE
Output:

Hello GFG

The escape sequence “\t” is very frequently used in loop based pattern printing programs.
// C program to illustrate

// \v escape sequence

#include <stdio.h>

int main(void)

// Here we are using \v, which

// is vertical tab character.

printf("Hello friends");

printf("\v Welcome to GFG");

return (0);

Run on IDE
Output:
Hello Friends

Welcome to GFG

// C program to illustrate \r escape

// sequence

#include <stdio.h>

int main(void)

// Here we are using \r, which

// is carriage return character.

printf("Hello fri \r ends");

return (0);

Run on IDE
Output: (Depend upon compiler)

ends

// C program to illustrate \\(Backslash)

// escape sequence to print backslash.

#include <stdio.h>

int main(void)

// Here we are using \,

// It contains two escape sequence

// means \ and \n.

printf("Hello\\GFG");

return (0);

Run on IDE
Output: (Depend upon compiler)

Hello\

GFG

Explanation : It contains two escape sequence means it after printing the \ the compiler read the
next \ as as new line character i.e. \n, which print the GFG in the next line
// C program to illustrate \' escape
// sequence/ and \" escape sequence to

// print single quote and double quote.

#include <stdio.h>

int main(void)

printf("\' Hello Geeks\n");

printf("\" Hello Geeks");

return 0;

Run on IDE
Output:

' Hello Geeks

" Hello Geeks

// C program to illustrate

// \? escape sequence

#include <stdio.h>

int main(void)

// Here we are using \?, which is

// used for the presentation of trigraph

// in the early of C programming. But

// now we don't have any use of it.

printf("\?\?!\n");

return 0;

Run on IDE
Output:

??!

// C program to illustrate \OOO escape sequence

#include <stdio.h>

int main(void)

// we are using \OOO escape sequence, here


// each O in "OOO" is one to three octal

// digits(0....7).

char* s = "A\0725";

printf("%s", s);

return 0;

Run on IDE
Output:

A:5

Explanation : Here 000 is one to three octal digits(0….7) means there must be atleast one octal digit
after \ and maximum three.Here 072 is the octal notation, first it is converted to decimal notation that is
the ASCII value of char ‘:’. At the place of \072 there is : and the output is A:5.
// C program to illustrate \XHH escape

// sequence

#include <stdio.h>

int main(void)

// We are using \xhh escape sequence.

// Here hh is one or more hexadecimal

// digits(0....9, a...f, A...F).

char* s = "B\x4a";

printf("%s", s);

return 0;

Run on IDE
Output:

BJ

Explanation : Here hh is one or more hexadecimal digits(0….9, a…f, A…F).There can be more than
one hexadecimal number after \xHere’\x4a’ is a hexadecimal number and it is a single char. Firstly it
will get converted in to decimal notation and it is the ASCII value of char ‘J’. Therefore at the place of
\x4a, we can write J. So the output is BJ.

C/C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified
as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. Keyword: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred names
for a compiler, they can’t be used as variable names because by doing so, we are trying to assign
a new meaning to the keyword which is not allowed. You cannot redefine keywords. However,
you can specify text to be substituted for keywords before compilation by using C/C++
preprocessor directives.C language supports 32 keywords which are given below:
2.
3. auto double int struct
4. break else long switch
5. case enum register typedef
6. char extern return union
7. const float short unsigned
8. continue for signed void
9. default goto sizeof volatile
10. do if static while

While in C++ there are 31 additional keywords other than C Keywords they are:

asm bool catch class


const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

11. Identifiers: Identifiers are used as the general terminology for naming of variables, functions
and arrays. These are user defined names consisting of arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved
for special use. Once declared, you can use the identifier in later program statements to refer to
the associated value. A special kind of identifier, called a statement label, can be used in goto
statements.

There are certain rules that should be followed while naming c identifiers:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special
character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are significant.
Some examples of c identifiers:

NAME REMARK

_A9 Valid

Temp.var Invalid as it contains special character other than the underscore


void Invalid as it is a keyword

C program:

void main()

int a = 10;

In the above program there are 2 identifiers:


6. main: method name.
7. a: variable name.
12. Constants: Constants are also like normal variables. But, only difference is, their values can
not be modified by the program once they are defined. Constants refer to fixed values. They are
also called as literals.
Constants may belong to any of the data type.Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
0. Integer constants – Example: 0, 1, 1218, 12482
1. Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
2. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
3. Character constants -Example: ‘a’, ‘A’, ‘z’
4. String constants -Example: “GeeksforGeeks”
13. Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).This
null character indicates the end of the string. Strings are always enclosed in double quotes.
Whereas, a character is enclosed in single quotes in C and C++.Declarations for String:
 char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;
Difference between above declarations are:
3. when we declare char as “string[20]”, 20 bytes of memory space is allocated
for holding the string value.
4. When we declare char as “string[]”, memory space will be allocated as per the
requirement during execution of the program.
14. Special Symbols: The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = #
 Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls and
function parameters.
 Braces{}: These opening and ending curly braces marks the start and end of
a block of code containing more than one executable statement.
 comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
 semi colon : It is an operator that essentially invokes something called an
initialization list.
 asterick (*): It is used to create pointer variable.
 assignment operator: It is used to assign values.
 pre processor(#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
15. Operators: Operators are symbols that triggers an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
 Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.For Example increment and decrement
operators
 Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators: These operators requires three operands to act upon. For
Example Conditional operator(?:).

Das könnte Ihnen auch gefallen