PSWC Unit I Full

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Problem Solving With C

Compiled by
M S Anand

Department of Computer Science &


Engineering
Problem Solving With C
Introduction

Text Book(s):
1. “How To Solve It By Computer”, R G Dromey, Pearson, 2011.
2. “The C Programming Language”, Brian Kernighan, Dennis
Ritchie, 2nd Edition, Prentice Hall PTR, 1988.

Reference Book(s):
1. “Expert C Programming; Deep C secrets”, Peter van der Linden
2. “ The C puzzle Book”, Alan R Feuer

11/03/2024
Problem Solving With C
Introduction

The Syllabus is here: Syllabus

The course evaluation policy: Eval

11/03/2024
Problem Solving With C
Introduction

Why study C?
C is one of the most important programming languages in the
history of computing.

C provided the basis for a number of other languages which


followed it.

C was born out of necessity.


Dennis Ritchie (Bell Labs AT & T) (in the 1960s) - developed
Multics (an Operating System) using assembly language. Not cost
effective – the project was dropped by Bell.

Ritchie, Ken Thompson and Brian Kernighan – created UNIX using


assembly language, Fortran and a language called ‘B’.

11/03/2024
Problem Solving With C
Introduction

UNIX which was totally written in assembly language was rewritten


using the ‘B language. To overcome the limitations of the B
language, C language was developed in 1971-73.

The name C was chosen because it succeeded B.

In its early days, C was designed keeping UNIX in mind. C was


used to perform tasks and operate UNIX.

So, keeping performance and productivity in mind, many of the


UNIX components were rewritten in C from assembly language.

For example, the UNIX kernel itself was rewritten in 1973 on a DEC
PDP-11.

11/03/2024
Problem Solving With C
Introduction

Ritchie and Kernighan documented their creation in the form of a


book called "The C Programming Language."

Evolution of C
Over time, C began to be used in personal computers for
developing software applications and other purposes.

Major applications like Adobe Photoshop, Mozilla Firefox, MySQL


server, WinAMP media player, Bloomberg RDBMS and a lot more –
written mostly using C.

C has also influenced the development of numerous languages


such as AWK, csh, C++, C#, JavaScript, etc.

Nearly all modern operating systems are written in C. It is also


widely used in embedded systems, such as those found in
vehicles, smart TVs and countless internet of things (IoT) devices.
11/03/2024
Problem Solving With C
Introduction

Unlike many programming languages that are now extinct or almost


extinct, C has stood the test of time and thrived.

Even powerful technology waves like IoT, AI and automation have


failed to dislodge C from its position of prominence.

It appears that this language will continue to be with us long into the
future as well.

Proof (??)
The TIOBE Programming Community index is an indicator of the
popularity of programming languages. The index is updated once a
month. The ratings are based on the number of skilled engineers
world-wide, courses and third party vendors.

Jan 2024 – The four most popular programming languages are


Python, C, C++ and Java, in that order.
11/03/2024
Problem Solving With C
Timeline of C

11/03/2024
Problem Solving With C
C Standards

The C programming language has several standard versions, with the most
commonly used ones being C89/C90, C99, C11, and C18.
❑ C89/C90 (ANSI C or ISO C) was the first standardized version of the
language, released in 1989 and 1990, respectively. This standard
introduced many of the features that are still used in modern C
programming, including data types, control structures, and the standard
library.
❑ C99 (ISO/IEC 9899:1999) introduced several new features, including
variable-length arrays, flexible array members, complex numbers, inline
functions, and designated initializers. This standard also includes
several new library functions and updates to existing ones.
❑ C11 (ISO/IEC 9899:2011) introduced several new features, including
_Generic, static_assert, and the atomic type qualifier. This standard also
includes several updates to the library, including new functions for math,
threads, and memory manipulation.
❑ C18 (ISO/IEC 9899:2018) is the most recent standard and includes
updates and clarifications to the language specification and the library.

11/03/2024
Problem Solving With C
Programming language

A programming language is a system of notation for writing computer


programs.

High-level vs. low-level languages


The biggest factor that differentiates high- and low-level programming
languages is whether the language is meant to be easily understood by a
human programmer or a computer.
❖ Low-level languages are machine-friendly, which makes them highly
efficient in terms of memory usage but highly difficult to understand by a
programmer. Since they're not very people-friendly because they don't
use human language, they are not most commonly used.
Example – any assembly language.
❖ High-level languages - are less memory efficient but much more
human-friendly. This programming style makes it easier to write,
understand, maintain, and debug. Most popular programming languages
in use today are considered high-level languages.

11/03/2024
Problem Solving With C
Programming language

Interpreted vs. compiled languages


The distinction between interpreted and compiled languages has to
do with how they convert high-level code and make it readable by a
computer.
▪ With interpreted languages, code goes through a program
called an interpreter, which reads and executes the code line by
line. This tends to make these languages more flexible and
platform independent.
Examples of interpreted languages include:
Python, JavaScript, PHP, Ruby
▪ Compiled languages go through a build step where the entire
program is converted into machine code. This makes it faster to
execute, but it also means that you have to compile or "build" the
program again anytime you need to make a change.
Examples of compiled languages include:
C, C++, and C#, Rust, Erlang
11/03/2024
Problem Solving With C
Programming language

11/03/2024
Problem Solving With C
Programming language

Where does ‘C fit in?


C is usually called a middle-level language as it stands between
high-level languages and low-level languages.
▪ C language instructions resemble the normal algebraic
expressions along with certain English keywords like if, else, for,
etc. In this respect, C resembles a high-level language.
▪ It also has certain low-level features that help the programmers
to carry out operations available in assembly or machine
languages. For example, it permits the manipulation of individual
bits and also values of certain variables can be sorted within the
CPU's registers to speed up the computation associated with
these values.

Thus, C can be used for systems programming (eg., for writing


operating systems) as well as applications programming (e.g. to
solve a complicated system of mathematical equations, or for
writing a program to bill customers).
11/03/2024
Problem Solving With C
Main features of C

11/03/2024
Problem Solving With C
Creating and executing a C program

Creating C Programs
There are four fundamental stages, or processes, in the creation of
any C program:
1. Editing
2. Compiling
3. Linking
4. Executing

The processes of editing, compiling, linking, and executing are


essentially the same for developing programs in any environment
and with any compiled language. Figure (next slide) summarizes
how you would typically pass through processes as you create your
own C programs.

11/03/2024
Problem Solving With C
Creating and executing a C program

11/03/2024
Problem Solving With C
Creating and executing a C program

Editing
Editing is the process of creating and modifying C source code—
the name given to the program instructions you write. Some C
compilers come with a specific editor program that provides a lot of
assistance in managing your programs.

Compiling
The compiler converts your source code into machine language
and detects and reports errors in the compilation process. The input
to this stage is the file you produce during your editing, which is
usually referred to as a source file.

Compilation is a two-stage process. The first stage is called the


preprocessing phase, during which your code may be modified or added to,
and the second stage is the actual compilation that generates the object
code. Your source file can include preprocessing macros, which you use to
add to or modify the C program statements.
11/03/2024
Problem Solving With C
Creating and executing a C program

Linking
The linker combines the object modules generated by the compiler from
source code files, adds required code modules from the standard library
supplied as part of C, and welds everything into an executable whole. The
linker also detects and reports errors; for example, if part of your program
is missing or a nonexistent library component is referenced.

Executing
The execution stage is where you run your program, having completed all
the previous processes successfully. Unfortunately, this stage can also
generate a wide variety of error conditions that can include producing the
wrong output, just sitting there and doing nothing, or perhaps crashing your
computer for good measure. In all cases, it’s back to the editing process to
check your source code.

Debugging
Find the errors and fix them.

11/03/2024
Problem Solving With C
Setting up the development environment

We will use the gcc compiler

On Linux systems, gcc is installed, by default.

On Windows systems, we need to install a “gcc” compatible


compiler or a port of gcc on Windows.

We will use MinGW - Minimalist GNU for Windows


MinGW: A native Windows port of the GNU Compiler Collection (GCC),
with freely distributable import libraries and header files for building native
Windows applications; includes extensions to the MSVC runtime to support
C99 functionality. All of MinGW's software will execute on the 64bit
Windows platforms.

You can download this compiler from:


https://sourceforge.net/projects/mingw/
Installation: Just double-click the downloaded file and follow the
instructions.
11/03/2024
Problem Solving With C
Case study

Refer to airport

11/03/2024
Problem Solving With C
The first program

The very first program in C

/* Your very First C Program - Displaying Hello World */


#include <stdio.h>
int main(void)
{
printf("Hello world!\n");
return 0;
} // store this in a file called hello.c

Create the executable (a.exe on Windows and a.out on Linux – by


default)

gcc hello.c

Invoke the program by typing either a.exe (on Windows) or ./a.out


(on Linux), at the command prompt.
11/03/2024
Problem Solving With C
Typical structure of a C program

There are 6 basic sections responsible for the proper execution of a


program. The sections are:

1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs (other functions)

A sample program with all the sections is here.

We will mostly stick to C11 version.

11/03/2024
Problem Solving With C
Compilation – a few options

Compilation

gcc –E source_file
The output after preprocessing is done

gcc –c source_file
Output file is an object file

gcc source_file
Executable file (if there were no errors)

gcc –o myexec source_file


Specifying a user defined name for the executable

11/03/2024
Problem Solving With C
Constants and variable types

#define COUNT 100

char – signed and unsigned

int – signed and unsigned

short – signed and unsigned

long – signed and unsigned

float – Single precision floating point

double – Double precision floating point

long double

long long –

sizeof operator
11/03/2024
Problem Solving With C
Variables

What is a variable?
A variable in a program is a specific piece of memory that consists
of one or more contiguous bytes, typically 1, 2, 4, 8 or 16 bytes.

Every variable in a program has a name, which will correspond to


the memory address for the variable.

You use the variable name to store a data value in memory or


retrieve the data that the memory contains.

Naming Variables
The name you give to a variable, conveniently referred to as a
variable name, can be defined with some flexibility.
A variable name is a sequence of one or more uppercase or
lowercase letters, digits, and underscore characters (_) that begin
with a letter (incidentally, the underscore character counts as a
letter).
11/03/2024
Problem Solving With C
Variables

Invalid variable names in C:


➢ Cannot start with a digit or special character.
➢ Cannot contain spaces or special characters.
➢ Cannot be a reserved word or keyword.

Keywords are words that are reserved in C because they have a


special meaning. You must not use keywords as names for
variables or other entities in your code. If you do, your compiler will
produce error messages.

List of keywords in C are shown in the next slide.

11/03/2024
Problem Solving With C
Reserved (key) words in C

11/03/2024
Problem Solving With C
Data types and range of values
Variable type Keyword Bytes required Range

Character char 1 -127 to 127

Unsigned character unsigned char 1 0 to 255

Integer int 2 (?) -32767 to 32767

Short integer short int 2 -32767 to 32767

Long integer long int 4 -2,147,483,648 to 2,147,483,647

Unsigned integer unsigned int 2(?) 0 to 65535

Unsigned short integer unsigned short 2 0 to 65535

Unsigned long integer unsigned long 4 0 to 4,294,967,295

float float 4 -3.4E+38 to +3.4E+38


double double 8 -1.7E+308 to +1.7E+308
Long long long long 8

Long double long double 16

11/03/2024
Problem Solving With C
Basic input and output in C

int getchar(void) - reads the next available character from the


keyboard and returns it as an integer.
Reads only single character at a time.
Use this method in the loop in case you want to read more than one
character from the keyboard.

int putchar(int c) - puts the passed character on the screen and


returns the same character.
Puts only single character at a time.
Use this method in the loop in case you want to display more than
one character on the screen.

A sample program is here

11/03/2024
Problem Solving With C
Operators and Expressions

Operator performs an operation on data (operands). They are


classified into following −
➢ Arithmetic operators.
➢ Relational operators.
➢ Logical operators.
➢ Assignment operators.
➢ Increment and decrement operators.
➢ Bitwise operators.
➢ Conditional operators.
➢ Special operators.

11/03/2024
Problem Solving With C
Arithmetic Operators

Operator Description Example a = 32, b = 10 Result


+ Addition a+b 32 + 10 42
- Subtraction a–b 32 – 10 22
* Multiplication a*b 32 * 10 320
/ Division a/b 32 / 10 3
% Modulo division a%b 32 % 10 2

11/03/2024
Problem Solving With C
Relational Operators

These are used for comparing two expressions.


Operator Description Example a = 32, b = 10 Result
< Less than a<b 32 < 10 0
<= Less than or equal to a <= b 32 <=10 0
> Greater than a>b 32 > 10 1
>= Greater than or equal to a >= b 32 >= 10 0
== Equal to a == b 32 == 10 0
!= Not equal to a != b 32 != 10 1

The result of a logical operation is either True (1) or False (0) A sample program is
here.

11/03/2024
Problem Solving With C
Logical Operators

These are used to combine 2 (or) more expressions logically.


They are logical AND (&&) logical OR ( || ) and logical NOT (!)

Operator Description Example a = 20, b = 10, c=30 Result


&& Logical AND (a > b) && (a < c) (20 > 10) && (20 < 30) 1
|| Logical OR (a > b) || (c <= b) 32 <=10 1
! Logical NOT a>b 32 > 10 1

The result of a logical operation is either True (1) or False (0) A sample program is
here.

11/03/2024
Problem Solving With C
Assignment Operators

Assign a value to a variable.

=, +=, -=, *=, /=, %=

11/03/2024
Problem Solving With C
Increment and Decrement Operators

Increment operator (++)


pre increment - ++a
post increment – a++

Decrement operator − (- -)
pre decrement - --a
post decrement – a—

Sample programs:

preincr postincr

predecr postdecr

11/03/2024
Problem Solving With C
Bitwise Operators

Bitwise operators operate on bits.

11/03/2024
Problem Solving With C
Conditional (Ternary) Operator

exp1? exp2: exp3


If exp1 is true, exp2 is evaluated. Otherwise, exp3 is evaluated. Or
in the form of if-else.

if (exp1)
exp2;
else
exp3;

An example program is ex_ternary.c

11/03/2024
Problem Solving With C
Special Operators

Special operators
Some of the special operators are comma, ampersand (&), sizeof
operators.

Comma ( , ) − It is used as separator for variables. For example;


a=10, b=20

Address (&) − It get the address of a variables.

sizeof ( ) − It used to get the size of a data type of a variable in


bytes.

11/03/2024
Problem Solving With C
Control statements

The primary types of control statements in C are:

Decision-making control statements


➢ Simple if statement
➢ if-else statements
➢ Nested if-else statements
➢ else-if ladder

Conditional statements - switch-case

goto statements in C

Loop control statements in C


➢ while Loop
➢ do-while Loop
➢ for Loop

11/03/2024
Problem Solving With C
Control statements

if Statement

if (test expression)
{
// code
}

if...else Statement

if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}

Sample program is check_odd.c


11/03/2024
Problem Solving With C
Control statements

if...else Ladder
if (test expression1) {
// statement(s)
}
else if(test expression2) {
// statement(s)
}
else if (test expression3) {
// statement(s)
}
.
.
else {
// statement(s)
}

Sample program is check_grade.c


11/03/2024
Problem Solving With C
Control statements

Nested if...else
It is possible to include an if...else statement inside the body of
another if...else statement.

11/03/2024
Problem Solving With C
Conditional statements
C switch Statement
The switch statement allows us to execute one code block among many
alternatives.

You can do the same thing with the if...else..if ladder. However, the syntax
of the switch statement is much easier to read and write.

switch (expression)
​{
case constant1:
// statements
break;

case constant2:
// statements
break;
.
.
.
default:
// default statements
} A sample program is here.
11/03/2024
Problem Solving With C
goto statement

The goto statement allows us to transfer control of the program to


the specified label.

Syntax of goto Statement


goto label;
... .. ...
... .. ...
label:
statement;

The label is an identifier. When the goto statement is encountered,


the control of the program jumps to label: and starts executing the
code.

A sample program is print_table.c

11/03/2024
Problem Solving With C
Loop statements

Three types of loops:

for loop

while loop

do...while loop

11/03/2024
Problem Solving With C
Loop statements

for loop
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}
How does the for loop work?
✓ The initialization statement is executed only once.
✓ Then, the test expression is evaluated. If the test expression is
evaluated to false, the for loop is terminated.
✓ However, if the test expression is evaluated to true, statements
inside the body of the for loop are executed, and the update
expression is updated.
✓ Again the test expression is evaluated.

This process goes on until the test expression is false. When the
test expression is false, the loop terminates.
Sample program: find_ones1.c
11/03/2024
Problem Solving With C
Loop statements

while loop
while (testExpression) {
// the body of the loop
}
How does the while loop work?
✓ The while loop evaluates the testExpression inside the
parentheses ().
✓ If testExpression is true, statements inside the body of while loop
are executed. Then, testExpression is evaluated again.
✓ The process goes on until testExpression is evaluated to false.
✓ If testExpression is false, the loop terminates (ends).

Sample program: find_ones2.c

11/03/2024
Problem Solving With C
Loop statements
do...while loop
The do..while loop is similar to the while loop with one important
difference. The body of do...while loop is executed at least once.
Only then, the test expression is evaluated.

do {
// the body of the loop
}
while (testExpression);

How does do...while loop work?


➢ The body of do...while loop is executed once. Only then, the
testExpression is evaluated.
➢ If testExpression is true, the body of the loop is executed again
and testExpression is evaluated once more.
➢ This process goes on until testExpression becomes false.
➢ If testExpression is false, the loop ends. find_ones3.c
11/03/2024
Problem Solving With C
Loop statements

break and continue


The break statement ends the loop immediately when it is
encountered. Its syntax is:

break; find_ones4.c

The break statement is almost always used with if...else statement


inside the loop.

The continue statement skips the current iteration of the loop and
continues with the next iteration. Its syntax is:

continue;

The continue statement is almost always used with the if...else


statement. ex_continue.c

11/03/2024
Problem Solving With C
Loop statements

Write a program to find the number of bits set to 1 and number of


bits set to 0, in a given integer.

find_ones_zeros.c

11/03/2024
Problem Solving With C
Basic Input/Output functions

Input

getchar () and scanf ()

Output

putchar() printf ()

11/03/2024
Problem Solving With C
Basic Input/Output functions

getchar ()

getchar — get a byte from a stdin stream

#include <stdio.h>

int getchar(void);

putchar ()

int putchar(int c)

writes the character c, cast to an unsigned char, to stream.

Sample program: basic_input.c basic_output.c

11/03/2024
Problem Solving With C
Basic Input/Output functions

Write a program that reads an integer entered by the user and


displays it in octal.

Write a program that asks the user to enter a fraction, then reduces
the fraction to lowest terms. (Example 6/12 to be reduced to ½)
Hint: To reduce a fraction to lowest terms, we need to divide both
the numerator and the denominator by the GCD of the numerator
and the denominator).

Write a program to calculate the length of a sentence which you will


key in (Use getchar() to read the input).

Write a program that counts the number of vowels present in a


sentence which you key in (Use getchar() to read the input).

Write a program that calculates the average word length in a


sentence keyed in by you (Use getchar() to read the input).
11/03/2024
Problem Solving With C
Some programming exercises

Write a program that asks the user to key in time in a 24 hour


format and then displays it in 12 hour format with AM and PM
clearly defined. Be careful not to display 12:00 as 0:0

Write a program that prompts the user to enter two dates and then
indicates which date comes earlier in the calendar.

Write a program that prompts the user to enter a 2 digit number and
then prints the English word for the number.

Write a program that uses Newton’s method to calculate the square


root of a positive floating point number
Algorithm - Take a reasonable guess (approximate root) for the square root.
Add the approximate root with the original number divided by the approximate root
and divide by 2.
x_i := (x_i + n / x_i) / 2
Continue step 2 until the difference in the approximate root along the iterations is
less than the desired value (or precision value).
The approximate root is the square root we want.
11/03/2024
Problem Solving With C
Language specification and behavior

In computer programming, a programming language specification


(or standard or definition) is a documentation artifact that defines a
programming language so that users and implementors can agree
on what programs in that language mean.

Specifications are typically detailed and formal, and primarily used


by implementors, with users referring to them in case of ambiguity

11/03/2024
Problem Solving With C
Language specification and behavior

A specification is a document in human language describing how a


system is supposed to work.

In the case of a programming language, it describes how the


compiler or interpreter is to react to various inputs - which are
valid/invalid, and what happens when they are executed.

Language Specification
A programming language specification can take several forms,
including the following:
➢ An explicit definition of the syntax and semantics of the
language.
➢ A description of the behavior of a "translator” for the language
➢ “Model implementation” is a program that implements all
requirements from a corresponding specification

11/03/2024
Problem Solving With C
Language specification and behavior
Categories of programs by behavior
The original goal of the C standard committee in the early 1980s was to
codify the set of rules in existing implementations. This standardization was
possible for features in the original ”Kernighan and Ritchie C
manual” where compilers and runtime libraries all agreed on their
interpretation, but became more difficult when the compilers and libraries
diverged from it. Some diverged because the manual was ambiguous,
others to provide extensions useful for their target environment or CPU.

The committee was cautious to minimize disruption, both to existing


implementations and to the large body of C code out there. But the
committee did not want to diminish the value of conformance. Therefore,
the committee introduced the notion of degrees of conformance. Although
all implementations must conform to the standard, programs can choose to
conform to varying degrees, and with varying guarantees for code
portability.

11/03/2024
Problem Solving With C
Language specification and behavior
To that end, the C standard recognizes several categories of programs.
Each category in turn places progressively weaker requirements on
implementations, and, as a result, weaker guarantees about programs'
behavior and portability.

Terminology:
✓ An implementation consists of a compiler and the standard C library.
The C library rarely stands on its own but is usually incorporated into a
larger library that implements some superset of C such as POSIX, or
some proprietary operating system API.
✓ By behavior, the standard means the observable output of a program:
The data it writes to open streams (such as stdout and stderr), or the
accesses it performs on volatile storage (both reading from it and writing
to it).
✓ Formally, the term behavior is defined as external appearance or action.
✓ Finally, the term portability is defined in the ISO vocabulary as
the capability of a program to be executed on various types of data
processing systems without converting the program to a different
language and with little or no modification.
11/03/2024
Problem Solving With C
Language specification and behavior
Well-defined behavior
Ideally, a program is portable without change, not just to the environments
intended for it, but to all possible environments, whether or not they exist in
the wild, ever did, or might in the future. Given the same input, a portable
program runs with the same output everywhere it's compiled today, and will
continue to do so in the future. Another way we can describe a portable
program like this is to call it well-defined.

Portable programs provide the strongest guarantees to their users. To


ensure these guarantees, portable programs must:
➢ Consist only of code with well-defined syntax and rely only on constructs with
well-defined semantics.
➢ Adhere to all the most stringent requirements of the C standard, and therefore:
▪ Either make no unconditional uses of any optional features specified by the
standard, or guard the use of each feature by the appropriate
__STDC_XXX__ feature test macro.
▪ Use no implementation extensions.
▪ Stay within all minimum implementation limits specified by the standard.

11/03/2024
Problem Solving With C
Language specification and behavior
Unspecified behavior
The standard describes a few dozen coding constructs that might result in
more than one kind of behavior. A couple of examples are whether the
same string literals have distinct addresses, or the order in which
subexpressions are evaluated. Uses of these constructs are valid code that
implementations might handle in different ways that can even change from
one instance to another. Because the identified constructs are valid code,
their handling doesn't extend to issuing an error, either during compilation
or at runtime.

A program with unspecified behavior is a program that is correct according


to the standard, but that contains one or more coding constructs with
unspecified behavior. Such a program must run successfully on every
implementation (i.e., it must not crash—or trap, in the parlance of the
standard—or otherwise misbehave), but could have different output from
one execution to another.

An example is here.

11/03/2024
Problem Solving With C
Language specification and behavior
Implementation-defined behavior
Besides constructs with undefined behavior, the standard also describes a
number of others that might result in more than one observable behavior,
but where implementations are required to document how each instance is
handled.

It should be emphasized that, just like the programs with unspecified


behavior that we discussed in the previous section, a program with
implementation-defined behavior is a valid program that must run
successfully. It must not crash or otherwise misbehave.

This category is less useful than it seems. First, simply because a


construct's behavior is documented doesn't make the construct portable, so
relying on it doesn't improve the portability of a program. And second, not
all implementations follow the requirement to document their choices.

Example.
printf("Size of int: %d\nSize of char:%d\n", sizeof(int), sizeof(char));

11/03/2024
Problem Solving With C
Language specification and behavior

Locale-specific behavior
Locale-specific behavior is behavior that arises when a program
runs in a locale other than the default C locale. An example locale is
fr_CA for Canadian French. This behavior is a special category that
C programs opt into, either by being translated in a specific locale,
or at runtime by calling the setlocale function with a first argument
other than "C".

Implementations are expected to document the behavior of


programs in specific locales. We will not consider this category
further; it's effectively a special case of well-defined behavior where
the output of a program can change from one environment (locale)
to another.

11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior
The C standard describes programs that contain an undefined construct as either
nonportable or erroneous. The practical difference is that nonportable programs run
correctly (don't crash or misbehave), perhaps even with the expected output, in
some environments. In contrast, erroneous programs might (although they don't
need to) behave erratically or crash.

Most real-world programs fall into the undefined category: They contain some code
whose behavior is not defined by the C standard. This isn't necessarily a bad thing.
The behavior may be defined by some other standard or provided as an extension of
the implementation targeted by the program's authors.

However, these assurances don't change the categorization of the program as


undefined under the rules of the C standard. The behavior may also seem to be
defined by a given implementation, in the sense that the construct and the program
behave as the programmer intended. But unless the implementation documents as
an extension the behavior of the construct under the conditions the standard doesn't
specify, it should be considered erroneous.

11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior
Some of the undefined behaviour are :

Division by zero
Ex. : printf("%d\n", 5 / 0);

Signed integer overflow


Ex. :printf("Size of int: %d\n", INT_MAX + 1);

Null pointer dereference


Ex. : int *ptr = NULL;
printf("%d", *ptr);

Memory access outside of array bounds


Ex.: int arr[5] = {0, 1, 2, 3, 4};
printf("%d", arr[7])

11/03/2024
Problem Solving With C
Language specification and behavior
Undefined behavior can be broken down into two kinds: compile-time
undefined behavior and runtime undefined behavior.

Compile-time undefined behavior


Compile-time undefined behavior refers to the behavior of constructs that
are processed during translation, such as preprocessing directives or the
evaluation of constant expressions. An example of nonportable compile-
time undefined behavior is the use of an implementation-specific literal,
such as a binary constant like 0b101010 with GCC (prior to C23). An
example of erroneous compile-time undefined behavior (in popular
compilers like Clang and GCC) is the following definition:

enum { e, f, g = f / e };

The semantics of the division expression are undefined when the second
operand is zero. Because the compiler evaluates this division expression to
process the definition of the enumeration, the problem occurs at compile
time.

11/03/2024
Problem Solving With C
Language specification and behavior

Runtime undefined behavior


Runtime undefined behavior, on the other hand, refers to the
outcome of a construct during program execution. An example of
nonportable runtime undefined behavior that's pervasive in almost
all programs is calling a library function that's defined neither in the
program nor by the C standard, such POSIX popen.

Another example of runtime undefined behavior is calling the C


standard printf function with a format directive whose behavior is
undefined in the C standard but defined by some other standard
such as POSIX. An example is %2$d:%1$d, used by POSIX to
reorder the subsequent arguments in the output. Similar examples
involve calling nonstandard functions that are either provided as
intrinsics by the compiler or defined by the target system.

11/03/2024
THANK YOU

M S Anand
Department of Computer Science Engineering
[email protected]

You might also like