This document provides an overview of the key differences between C and C++. It discusses how C lacks many high-level features that are present in C++, such as classes, templates, exceptions, and the standard library. However, it notes that C can still be used to write useful code by emulating high-level techniques. The document also summarizes some of the main language constructs in C like functions, printf/scanf, arrays, pointers, and memory management. It aims to help C++ programmers understand how to work with C when necessary.
The document provides an overview of C programming basics including:
- A brief history of the C programming language and why it is commonly used in embedded systems.
- The basic structure of a C program including comments, header files, functions, and data types.
- How to declare and initialize variables in C including different data types.
- Operators and expressions in C including arithmetic, relational, logical, and bitwise operators.
- Decision making and control flow in C using if/else statements and switch cases.
- Instructions to ask questions and contact the instructor for help.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, comments, preprocessor directives, libraries and headers. It also covers pointers, arrays, passing command line arguments and standard header files in C. Examples of simple C programs are provided to illustrate various concepts.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like main functions, libraries, headers, source/header files. It also covers basic C concepts like data types, variables, operators, functions, pointers, arrays, comments and preprocessor directives. Examples of simple C programs are provided to illustrate these concepts.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
The document discusses resource acquisition and initialization (RAII) in C++. It explains that resources like memory, handles, locks etc. need to be acquired and released properly to prevent leaks. The RAII pattern uses object destructors to ensure resources are released deterministically even after exceptions. It demonstrates using classes to represent resources that acquire the resource in the constructor and release it in the destructor. Finally, it discusses how languages like C# and Java implement disposal patterns and how scope guard can provide an alternative to unique_ptr for resource management in C++.
Difference between c# generics and c++ templatesUmar Ali
C# generics and C++ templates have several key differences:
1) C# generics are strongly typed while C++ templates are loosely typed.
2) C# generics are instantiated at runtime while C++ templates are instantiated at compile time.
3) C++ templates allow type parameters to have default values but C# generics do not.
4) Libraries can be created using C# generics but not with C++ templates since templates must be expanded at compile time.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
The C programming language was designed in the early 1970s and influenced by other languages. It is traditionally used for systems programming but is also used for other applications. The document provides an introduction to C including its standardization, differences between C and C++, elements of a C program including main functions and return values, and use of header files. It also discusses pointers, arrays, preprocessor directives, and macros.
The document provides an overview of C programming basics including:
- A brief history of the C programming language and why it is commonly used in embedded systems.
- The basic structure of a C program including comments, header files, functions, and data types.
- How to declare and initialize variables in C including different data types.
- Operators and expressions in C including arithmetic, relational, logical, and bitwise operators.
- Decision making and control flow in C using if/else statements and switch cases.
- Instructions to ask questions and contact the instructor for help.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, comments, preprocessor directives, libraries and headers. It also covers pointers, arrays, passing command line arguments and standard header files in C. Examples of simple C programs are provided to illustrate various concepts.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like main functions, libraries, headers, source/header files. It also covers basic C concepts like data types, variables, operators, functions, pointers, arrays, comments and preprocessor directives. Examples of simple C programs are provided to illustrate these concepts.
This is Work-In-Progress. Developing a series of lectures on C++0x. This will augment my presentations on C++ and Design Pattern. First trial run was done at Interra, Noida in 2009
The document discusses resource acquisition and initialization (RAII) in C++. It explains that resources like memory, handles, locks etc. need to be acquired and released properly to prevent leaks. The RAII pattern uses object destructors to ensure resources are released deterministically even after exceptions. It demonstrates using classes to represent resources that acquire the resource in the constructor and release it in the destructor. Finally, it discusses how languages like C# and Java implement disposal patterns and how scope guard can provide an alternative to unique_ptr for resource management in C++.
Difference between c# generics and c++ templatesUmar Ali
C# generics and C++ templates have several key differences:
1) C# generics are strongly typed while C++ templates are loosely typed.
2) C# generics are instantiated at runtime while C++ templates are instantiated at compile time.
3) C++ templates allow type parameters to have default values but C# generics do not.
4) Libraries can be created using C# generics but not with C++ templates since templates must be expanded at compile time.
Object-Oriented Programming in Modern C++. Borislav Stanimirov. CoreHard Spri...corehard_by
Object-oriented programming has been criticized a lot. Every now and then some article or talk appears denouncing it and proclaiming that it's dead. This talk will do the opposite. It defends OOP and presents many modern libraries and concepts to show that it's very much alive and kicking.
The C programming language was designed in the early 1970s and influenced by other languages. It is traditionally used for systems programming but is also used for other applications. The document provides an introduction to C including its standardization, differences between C and C++, elements of a C program including main functions and return values, and use of header files. It also discusses pointers, arrays, preprocessor directives, and macros.
Object-oriented programming (OOP) is a programming paradigm that uses "objects" to model real-world entities. Key concepts of OOP include abstraction, inheritance, and polymorphism. C++ was created by Bjarne Stroustrup in 1979 as an extension of C with object-oriented capabilities. It supports both procedural and object-oriented programming. C++ has become one of the most popular and widely used general-purpose programming languages.
This document contains lecture notes on the C programming language. It covers topics such as basic data types, variables, operators, instructions like if/else and loops, functions, pointers, and more. The notes include examples to illustrate each concept and are intended to teach C programming.
C is a general-purpose programming language developed in the early 1970s. It was originally created for and used to write the UNIX operating system. C became widely popular due to its efficiency and ability to be compiled on a variety of computers. It is commonly used to write operating systems, compilers, and other lower-level systems programs. C programs are written in text files with a .c extension and compiled into machine-readable code using a C compiler. C supports basic data types like integers, floats, characters, and arrays, as well as user-defined functions, variables, statements, and expressions.
(8) cpp abstractions separated_compilation_and_binding_part_iNico Ludwig
- The Preprocessor – Symbols and Macros
- Problems with Preprocessor Macros
- The assert() Macro
- Including and #include Guards
- Translation Units
- The One Definition Rule (ODR)
- Separate Compilation
- The Make System
How to do Test-Driven Development in C illustrated by solving a Recently Used List kata.
Similar slides can be found here http://www.olvemaudal.com/talks
Programming C Language Tutorial. Its an Learning document for base programming. Its an copied data from some websites and books. I tried to make more easier through this documents.
The document provides an overview of the fundamentals of the C programming language including its history, development environment, basic program structure, data types, constants, variables, input/output functions, and more. It describes how C was developed in the 1970s and became widely popular. It also explains key elements like preprocessor directives, functions, statements, and basic syntax rules for writing C programs.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then discusses the history and development of C. Key features of C mentioned include its portability, speed, and ability to be extended by users. The document explains the role of compilers in converting C code to object code. It also includes examples of basic C programs and flowcharts, and covers C concepts like data types, variables, operators, and control structures. Overall, the document serves as an introduction to the C language, its history and basics.
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
JavaTpoint share a presentation of C Programming language for beginners and professionals. now in this slideshare you will be learned basics of c programming language, what is c programming language, history of c programming, installing turbo c, features of c programming language, datatypes of c language, operaters in c, control statement of c language, c language functions, c array, pointer in c programming, and structure and union.
C and C ++ Training in Ambala ! BATRA COMPUTER CENTREjatin batra
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide Best C and C ++ Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...Kamiya Toshihiro
Toshihiro Kamiya: An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and Analysis,
Proceedings of the 9th IEEE International Workshop on Software Clones (IWSC'15), pp. 1-7 (2015).
The document introduces some basic C++ idioms, rules, guidelines and best practices. The author notes that some items are based on their personal style preferences and the styles of groups they work with. The intention is to use the presentation to spark discussion, as it includes some controversial issues. Readers are encouraged to provide criticism of the example code presented.
C is a procedural programming language that does not support object-oriented programming features like polymorphism, operator overloading, or inheritance. C++ builds on C by adding object-oriented programming capabilities, including virtual functions, polymorphism, operator overloading, inheritance, and data abstraction through the use of classes and objects. Other differences include C++ supporting namespaces to avoid name collisions, more flexible input/output functions, and memory management using new/delete operators instead of malloc/free functions.
The document compares and contrasts the C and C++ programming languages. It notes that C was initially developed as a procedural language focused on algorithms and mathematics, while C++ was developed as an object-oriented extension of C focused on modeling real-world problems. It provides examples of simple programs in each language and describes some key differences, such as C++ supporting features like classes, inheritance, function overloading, and encapsulation that provide object-oriented capabilities not present in C. The document also defines some basic concepts of object-oriented programming.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.PVS-Studio
Cfront is a C++ compiler which came into existence in 1983 and was developed by Bjarne Stroustrup. At that time it was known as "C with Classes". Cfront had a complete parser, symbol tables, and built a tree for each class, function, etc. Cfront was based on CPre. Cfront defined the language until circa 1990. Many of the obscure corner cases in C++ are related to the Cfront implementation limitations. The reason is that Cfront performed translation from C++ to C. In short, Cfront is a sacred artifact for a C++ programmer. So I just couldn't help checking such a project.
This document provides an overview of graphics programming in C++ using the G3D library. It discusses that C++ is widely used for computer graphics and combines low-level and high-level features. It also introduces the G3D library, which is an open source cross-platform library for 3D graphics that handles much of the complex infrastructure. The document then provides tips for programmers with Java experience on some key differences between C++ and Java and aspects of C++ they should be aware of for graphics programming.
C and C++ are programming languages with many similarities but some key differences. They both use basic built-in data types and control structures. However, C++ supports object-oriented programming features like classes, data hiding, and inheritance that are not present in C. C++ also supports function overloading, namespaces, and references, which provide more flexibility than C at the cost of additional complexity. Overall, C++ can be seen as an enhancement of C with additional high-level programming capabilities.
The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.
This document discusses graphics classes and how shapes are implemented in C++. It describes:
- The display model where objects are "attached" to windows and the display engine draws the objects.
- The code organization with interface classes like Shape and implementation files.
- Key classes like Point, Line, Lines, Color, and Polylines. Lines represents a set of lines.
- Methods to add shapes, lines, and points. Color and Line_style are used to manipulate appearance.
- Examples that demonstrate creating and manipulating lines, grids, and polylines using these classes. Implementation details are also provided.
C Programming Language Step by Step Part 1Rumman Ansari
This document provides an overview of the C programming language. It discusses the history and development of C, starting with predecessors like ALGOL-60 and BCPL in the 1960s and 1970s. C was created in the early 1970s and the first C compiler was released in 1978. Since then, C has become widely used for system programming and is foundational to many other languages like C++ and Java. The document outlines some key advantages of C, like its efficiency and ability to handle low-level tasks. It also provides brief descriptions of common C programming concepts.
This document discusses building stronger learning communities through transforming school, parent, and student collaboration with technology. Decades of research show that parent involvement leads to higher student achievement, better attendance, and lower rates of bad behavior. Technology provides new ways to connect learning communities and make collaboration transparent beyond barriers of time and space. When students, parents, teachers, and community members actively learn together through sharing ideas on blogs and social media, it empowers all individuals to get smarter through their connections.
Object-oriented programming (OOP) is a programming paradigm that uses "objects" to model real-world entities. Key concepts of OOP include abstraction, inheritance, and polymorphism. C++ was created by Bjarne Stroustrup in 1979 as an extension of C with object-oriented capabilities. It supports both procedural and object-oriented programming. C++ has become one of the most popular and widely used general-purpose programming languages.
This document contains lecture notes on the C programming language. It covers topics such as basic data types, variables, operators, instructions like if/else and loops, functions, pointers, and more. The notes include examples to illustrate each concept and are intended to teach C programming.
C is a general-purpose programming language developed in the early 1970s. It was originally created for and used to write the UNIX operating system. C became widely popular due to its efficiency and ability to be compiled on a variety of computers. It is commonly used to write operating systems, compilers, and other lower-level systems programs. C programs are written in text files with a .c extension and compiled into machine-readable code using a C compiler. C supports basic data types like integers, floats, characters, and arrays, as well as user-defined functions, variables, statements, and expressions.
(8) cpp abstractions separated_compilation_and_binding_part_iNico Ludwig
- The Preprocessor – Symbols and Macros
- Problems with Preprocessor Macros
- The assert() Macro
- Including and #include Guards
- Translation Units
- The One Definition Rule (ODR)
- Separate Compilation
- The Make System
How to do Test-Driven Development in C illustrated by solving a Recently Used List kata.
Similar slides can be found here http://www.olvemaudal.com/talks
Programming C Language Tutorial. Its an Learning document for base programming. Its an copied data from some websites and books. I tried to make more easier through this documents.
The document provides an overview of the fundamentals of the C programming language including its history, development environment, basic program structure, data types, constants, variables, input/output functions, and more. It describes how C was developed in the 1970s and became widely popular. It also explains key elements like preprocessor directives, functions, statements, and basic syntax rules for writing C programs.
This document provides an overview of the C programming language. It begins with an outline of topics covered, then discusses the history and development of C. Key features of C mentioned include its portability, speed, and ability to be extended by users. The document explains the role of compilers in converting C code to object code. It also includes examples of basic C programs and flowcharts, and covers C concepts like data types, variables, operators, and control structures. Overall, the document serves as an introduction to the C language, its history and basics.
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
JavaTpoint share a presentation of C Programming language for beginners and professionals. now in this slideshare you will be learned basics of c programming language, what is c programming language, history of c programming, installing turbo c, features of c programming language, datatypes of c language, operaters in c, control statement of c language, c language functions, c array, pointer in c programming, and structure and union.
C and C ++ Training in Ambala ! BATRA COMPUTER CENTREjatin batra
Batra Computer Centre is An ISO certified 9001:2008 training Centre in Ambala.
We Provide Best C and C ++ Training in Ambala. BATRA COMPUTER CENTRE provides best training in C, C++, S.E.O, Web Designing, Web Development and So many other courses are available.
An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and ...Kamiya Toshihiro
Toshihiro Kamiya: An Execution-Semantic and Content-and-Context-Based Code-Clone Detection and Analysis,
Proceedings of the 9th IEEE International Workshop on Software Clones (IWSC'15), pp. 1-7 (2015).
The document introduces some basic C++ idioms, rules, guidelines and best practices. The author notes that some items are based on their personal style preferences and the styles of groups they work with. The intention is to use the presentation to spark discussion, as it includes some controversial issues. Readers are encouraged to provide criticism of the example code presented.
C is a procedural programming language that does not support object-oriented programming features like polymorphism, operator overloading, or inheritance. C++ builds on C by adding object-oriented programming capabilities, including virtual functions, polymorphism, operator overloading, inheritance, and data abstraction through the use of classes and objects. Other differences include C++ supporting namespaces to avoid name collisions, more flexible input/output functions, and memory management using new/delete operators instead of malloc/free functions.
The document compares and contrasts the C and C++ programming languages. It notes that C was initially developed as a procedural language focused on algorithms and mathematics, while C++ was developed as an object-oriented extension of C focused on modeling real-world problems. It provides examples of simple programs in each language and describes some key differences, such as C++ supporting features like classes, inheritance, function overloading, and encapsulation that provide object-oriented capabilities not present in C. The document also defines some basic concepts of object-oriented programming.
Celebrating 30-th anniversary of the first C++ compiler: let's find bugs in it.PVS-Studio
Cfront is a C++ compiler which came into existence in 1983 and was developed by Bjarne Stroustrup. At that time it was known as "C with Classes". Cfront had a complete parser, symbol tables, and built a tree for each class, function, etc. Cfront was based on CPre. Cfront defined the language until circa 1990. Many of the obscure corner cases in C++ are related to the Cfront implementation limitations. The reason is that Cfront performed translation from C++ to C. In short, Cfront is a sacred artifact for a C++ programmer. So I just couldn't help checking such a project.
This document provides an overview of graphics programming in C++ using the G3D library. It discusses that C++ is widely used for computer graphics and combines low-level and high-level features. It also introduces the G3D library, which is an open source cross-platform library for 3D graphics that handles much of the complex infrastructure. The document then provides tips for programmers with Java experience on some key differences between C++ and Java and aspects of C++ they should be aware of for graphics programming.
C and C++ are programming languages with many similarities but some key differences. They both use basic built-in data types and control structures. However, C++ supports object-oriented programming features like classes, data hiding, and inheritance that are not present in C. C++ also supports function overloading, namespaces, and references, which provide more flexibility than C at the cost of additional complexity. Overall, C++ can be seen as an enhancement of C with additional high-level programming capabilities.
The C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.
This document discusses graphics classes and how shapes are implemented in C++. It describes:
- The display model where objects are "attached" to windows and the display engine draws the objects.
- The code organization with interface classes like Shape and implementation files.
- Key classes like Point, Line, Lines, Color, and Polylines. Lines represents a set of lines.
- Methods to add shapes, lines, and points. Color and Line_style are used to manipulate appearance.
- Examples that demonstrate creating and manipulating lines, grids, and polylines using these classes. Implementation details are also provided.
C Programming Language Step by Step Part 1Rumman Ansari
This document provides an overview of the C programming language. It discusses the history and development of C, starting with predecessors like ALGOL-60 and BCPL in the 1960s and 1970s. C was created in the early 1970s and the first C compiler was released in 1978. Since then, C has become widely used for system programming and is foundational to many other languages like C++ and Java. The document outlines some key advantages of C, like its efficiency and ability to handle low-level tasks. It also provides brief descriptions of common C programming concepts.
This document discusses building stronger learning communities through transforming school, parent, and student collaboration with technology. Decades of research show that parent involvement leads to higher student achievement, better attendance, and lower rates of bad behavior. Technology provides new ways to connect learning communities and make collaboration transparent beyond barriers of time and space. When students, parents, teachers, and community members actively learn together through sharing ideas on blogs and social media, it empowers all individuals to get smarter through their connections.
This document is Travis McNaughton's education portfolio that outlines his qualifications and experiences in various areas of teaching. It includes sections on leadership, teaching strategies, relationships with students, parents and staff, extracurricular activities, assessment, professional development, technology use, discipline, and recognition of success. The portfolio demonstrates McNaughton's strengths in areas like leading professional learning communities, positive student relationships, use of differentiated instruction, assessment to inform planning, and embracing technology and lifelong learning.
This was shown during the first day of school for the students during the assembly as part of a presentation to the students. The presentation highlighted the "big rocks" of the school and challenged students to new levels of leadership this school year.
Muir Lake School, a part of Parkland School Division, is becoming a 1-to-1 BYOD learning community. The mission behind this initiative is "our students will innovate, collaborate, and be highly motivated about their learning". The goal is that every student will have access to a personal laptop in every class to use whenever it is the best tool for the learning activity. The initiative was piloted in grade 4 and grade 9 and will be expanding to all grades 4 through 9. This presentation outlines the "why" behind the initiative and first steps of Muir Lake School's journey. Google Doc Quick Link → bit.ly/MLS1to1
Building 1-to-1 BYOD Learning Communities Parent PresentationTravis McNaughton
A presentation designed specifically for parents sharing how and why technology should be in the classroom. The presentation invites parents to have their children participate in the 1 to 1 BYOD initiative at Muir Lake School. Presented in the spring of 2013.
This document provides an introduction to using Twitter for parents who want to engage in education. It outlines how Twitter can be used for communication, breaking news, activism, networking, discovery, research, and professional development. It then covers how to get started on Twitter, including creating an account, who to follow, hashtags, replying, mentioning, retweeting, and direct messaging. Finally, it provides tips for using Twitter like joining chats, using apps like TweetDeck, linking websites, and favoriting tweets.
This presentation is an introduction to a school professional development model that capitalizes on expertise within the school while empowering shared leadership and collaboration.
Transforming teaching & learning in 1 to-1 learning environmentsTravis McNaughton
Muir Lake school staff and students use technology to access, share and create knowledge, to discover, develop and apply competencies across subject areas for learning and to demonstrate what they know and are able to do. This presentation gives a brief overview how Muir Lake School implemented a grade 4-9 1:1 BYOD Learning environments and demonstrates the impact that this has had on students’ learning.
A microprocessor is a computer processor contained on a microchip. It contains the central processing unit (CPU) and performs arithmetic and logic operations. Microprocessors have evolved over generations from processing instructions serially to employing super scalar processing with over 10 million transistors. They are used in devices like computers, phones, and traffic lights to process instructions and control functions. The internal architecture of microprocessors like the Intel 8086 contains a bus interface unit that handles data transfer and an execution unit that decodes instructions and performs arithmetic logic operations.
This document discusses C and C++. It notes that both languages were created at Bell Labs and that C++ was designed to be as close to C as possible while adding object-oriented programming features. It outlines some key differences between C and C++, such as C++ supporting classes, templates, and exceptions while C does not. It also discusses common functions and libraries used in C like printf, scanf, strings, and memory management compared to C++.
THE C PROGRAMMING LANGUAGE PPT CONTAINS THE BASICS OF Cbhargavi804095
This document provides an overview of C programming and the differences between C and C++. It discusses how C and C++ were both developed at Bell Labs, how they are siblings but defined by separate standards committees. It summarizes some of the key differences between C and C++, such as C not having classes, templates, or exceptions. It also discusses various C programming concepts like functions, arrays, strings, memory management, standard libraries, and differences in const between C and C++.
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
This document discusses functions and header/source files in C++. It covers declarations, definitions, and the differences between them. Declarations introduce names and specify types, while definitions also fully specify the entity. Declarations allow interfaces to be specified. Headers contain declarations to share interfaces between parts of a program. Functions are described as units of operation that can take parameters and return values. The document also discusses scopes, namespaces, and storage classes like static.
Here is the corrected program:
#include <stdio.h>
int main( )
{
int i;
/* do some math */
i = 1 + 2 + 3;
/* do some more math */
i = i + i;
printf("i = %i \n", i);
}
/* desired output */
/*
i = 12
*/
This book contains C programming examples to teach C syntax and concepts. It is organized with simple programs first, building up concepts incrementally with each new example. The programs demonstrate individual language features rather than complete applications. The book assumes the reader already knows how to program and aims to show how to apply their existing skills to C.
The document provides an overview of basic C++ concepts including:
- C++ was developed as an extension of the C language and can be coded in an object-oriented or C-style.
- Keywords were added to support object-orientation, exceptions, and other features.
- Pointers in C++ store the address of a variable in memory.
- Blocks allow code sections to have their own local variables with minimized scope.
- Binding refers to converting functions/variables to machine addresses, which can be static/early or dynamic/late.
- Variables are statically scoped in C++ and type checking is done at compile-time rather than run-time.
- Most C++
The document provides an introduction to the C programming language, covering its history, uses, basic concepts, and key functions. It discusses how C was created at Bell Labs to develop the UNIX operating system, its widespread adoption, and importance. The document outlines common C data types, control flow statements like conditionals and loops, functions and their structure, and input/output functions like printf, scanf, gets and puts. It provides examples of basic C programs and how functions, conditionals, and I/O are implemented.
The document provides an introduction to the C programming language, including its history and evolution. It discusses key elements of C programs like functions, variables, data types, libraries, headers, and compilers. It also covers pointers, arrays, preprocessor directives, and macros. Examples are provided to illustrate basic C programs and common programming constructs in C.
This document is the table of contents for a book on C programming. It lists 88 example C programs that are intended to teach C concepts in an evolutionary manner. The programs cover basics like input/output, variables, data types, operators, loops, conditional statements, arrays, functions, pointers, structures, file I/O and more. The programs are presented from simplest to more complex to help programmers learn each new element of the C language.
The document outlines the aims and structure of an introductory programming course in C++. It introduces programming and discusses why C++ is a good first language to learn. It presents a simple "Hello World" program and discusses how it works, including compilation and execution. The course will cover fundamental programming concepts, techniques, and basic C++ facilities to enable students to write simple programs and learn other languages.
Contains C programming tutorial for beginners with lot of examples explained. This tutorial contains each and every feature of C programming that will help you. C programming tutorial covering basic C Programming examples, data types, functions, loops, arrays, pointers, etc.
C++ Unit 1PPT which contains the Introduction and basic o C++ with OOOps conc...ANUSUYA S
C++ is an object-oriented programming language that began as an expanded version of C. It was invented by Bjarne Stroustrup in 1979 at Bell Labs. C++ supports concepts of object-oriented programming like classes, inheritance, polymorphism, abstraction and encapsulation. It is a compiled, general purpose language that allows both procedural and object-oriented programming. Key features of C++ include input/output streams, declarations, control structures like if-else and switch statements.
The document provides an overview of the C++ programming language. It discusses that C++ was derived from C and created in the 1980s. It then describes some key aspects of C++ including the compiler, program structure, comments/directives like #include, data types, and the main program. The main program example provided converts miles to kilometers as a simple illustration of a C++ program.
The document discusses various topics related to C language including:
- Benefits and features of C like low-level operations, structured programming, and modular programming
- Data types in C like fundamental types (char, int, float), derived types, and defining variables
- Structure of C functions including single-level and multiple-level functions
- Input-output functions in C like character-based (getc, putc), string-based (gets, puts)
The document provides an introduction to the C programming language. It outlines the goals of learning C as being able to write simple programs, understand and modify existing code, and use makefiles. It then covers the basics of C syntax including variables, data types, functions, headers, comments, arithmetic operators, and input/output functions like printf and scanf. It introduces key concepts like compilation, declarations, arrays, and for loops. The overall document serves as a tutorial to teach the basic elements of the C language.
The document discusses principles of writing good C++ code. It begins by criticizing existing code examples as "ghastly style" that are difficult to understand and maintain. It advocates for a type-rich interface style with compact data structures and well-structured algorithms. The document also emphasizes writing code with modularity, effective resource management, and thread safety by default. The presentation provides examples demonstrating these principles using C++11 features like auto, type aliases, and literals.
Go is a new programming language designed for building concurrent and networked applications. It features garbage collection, static typing, and concurrency primitives like goroutines and channels. Go aims to provide the performance of compiled languages with the ease of use of interpreted dynamic languages. It shares similarities with C but with additional safety features and built-in concurrency support. Go is an open source project with an active community and documentation available online.
The document is a lecture on C programming given on August 17th, 2008 at IIT Kanpur by Deepak Majeti. It covers basics of C including data types, operators, input/output functions, and provides examples of simple C programs. It also discusses compilation, debugging errors, and homework problems involving operator precedence.
The document provides an overview of the C standard library. It includes a table listing common C standard library header files and briefly describing their purpose, such as <stdio.h> for input/output functions and <stdlib.h> for memory allocation and process control. The C standard library contains functions for tasks like string manipulation, mathematics, random numbers, memory management and more. It provides a standard library that is common across C implementations.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/building-and-scaling-ai-applications-with-the-nx-ai-manager-a-presentation-from-network-optix/
Robin van Emden, Senior Director of Data Science at Network Optix, presents the “Building and Scaling AI Applications with the Nx AI Manager,” tutorial at the May 2024 Embedded Vision Summit.
In this presentation, van Emden covers the basics of scaling edge AI solutions using the Nx tool kit. He emphasizes the process of developing AI models and deploying them globally. He also showcases the conversion of AI models and the creation of effective edge AI pipelines, with a focus on pre-processing, model conversion, selecting the appropriate inference engine for the target hardware and post-processing.
van Emden shows how Nx can simplify the developer’s life and facilitate a rapid transition from concept to production-ready applications.He provides valuable insights into developing scalable and efficient edge AI solutions, with a strong focus on practical implementation.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
1. Chapter 27
The C Programming Language
Bjarne Stroustrup
www.stroustrup.com/Programming
Dennis M. Ritchie
2. Abstract
This lecture gives you the briefest introduction to C
from a C++ point of view. If you need to use this
language, read an introductory book (e.g. K&R). This
lecture gives you a hint what to look for.
C is C++’s closest relative, and compatible in many
areas, so much of your C++ knowledge carries over.
Stroustrup/PPP - Oct'11 2
3. Overview
C and C++
Function prototypes
printf()/scanf()
Arrays and strings
Memory management
Macros
const
C/C++ interoperability
Stroustrup/PPP - Oct'11 3
4. dmr
C and C++
ken
bwk
bs
doug
…
Both were “born” in the Computer Science Research Department of
Bell Labs in Murray Hill, NJ
Stroustrup/PPP - Oct'11 4
5. Modern C and C++ are siblings
Stroustrup/PPP - Oct'11 5
6. C and C++
In this talk, I use “C” to mean “ISO C89”
That’s by far the most commonly used definition of C
Classic C has mostly been replaced (though amazingly not completely)
C99 is not yet widely used
Source compatibility
C is (almost) a subset of C++
Example of exception: int f(int new, int class, int bool); /* ok in C */
(Almost) all constructs that are both C and C++ have the same meaning
(semantics) in both languages
Example of exception: sizeof('a') /* 4 in C and 1 in C++ */
Link compatibility
C and C++ program fragments can be linked together in a single program
And very often are
C++ was designed to be “as close as possible to C, but no closer”
For ease of transition
For co-existence
Most incompatibilities are related to C++’s stricter type checking
Stroustrup/PPP - Oct'11 6
7. C and C++
Both defined/controlled by ISO standards committees
Separate committees
Unfortunately, leading to incompatibilities
Many supported implementations in use
Available on more platforms than any other languages
Both primarily aimed at and are heavily used for hard system
programming tasks, such as
Operating systems kernels
Device drivers
Embedded systems
Compilers
Communications systems
Stroustrup/PPP - Oct'11 7
8. C and C++
Here we
assume you know C++ and how to use it
describe the differences between C and C++
describe how to program using the facilities offered by C
Our ideal of programming and our techniques remain the same, but
the tool available to express our ideas change
describe a few C “traps and pitfalls”
don’t go into all the details from the book
Compatibility details are important, but rarely interesting
Stroustrup/PPP - Oct'11 8
9. C and C++
C++ is a general-purpose programming language with
a bias towards systems programming that
is a better C
supports data abstraction
supports object-oriented programming
supports generic programming
C:
Functions and structs
Machine model (basic types and operations)
Compilation and linkage model
Stroustrup/PPP - Oct'11 9
10. Missing in C (from a C++ perspective)
Classes and member functions
Use struct and global functions
Derived classes and virtual functions
Use struct , global functions, and pointers to functions
You can do OOP in C, but not cleanly, and why would you want to?
You can do GP in C, but why would you want to?
Templates and inline functions
Use macros
Exceptions
Use error-codes, error-return values, etc.
Function overloading
Give each function a separate name
new/delete
Use malloc()/free()
References
Use pointers
const in constant expressions
Use macros
Stroustrup/PPP - Oct'11 10
11. Missing in C (from a C++ perspective)
With no classes, templates, and exceptions, C can’t
provide most C++ standard library facilities
Containers
vector, map, set, string, etc.
Use arrays and pointers
Use macros (rather than parameterization with types)
STL algorithms
sort(), find(), copy(), …
Not many alternatives
use qsort() where you can
Write your own, use 3rd party libraries
Iostreams
Use stdio: printf(), getch(), etc.
Regular expression
Use a 3rd party library
Stroustrup/PPP - Oct'11 11
12. C and C++
Lots of useful code is written in C
Very few language features are essential
In principle, you don’t need a high-level language, you could write
everything in assembler (but why would you want to do that?)
Emulate high-level programming techniques
As directly supported by C++ but not C
Write in the C subset of C++
Compile in both languages to ensure consistency
Use high compiler warning levels to catch type errors
Use “lint” for large programs
A “lint” is a consistency checking program
C and C++ are equally efficient
If you think you see a difference, suspect differences in default optimizer
or linker settings Stroustrup/PPP - Oct'11 12
13. Functions
There can be only one function of a given name
Function argument type checking is optional
There are no references (and therefore no pass-by-reference)
There are no member functions
There are no inline functions (except in C99)
There is an alternative function definition syntax
Stroustrup/PPP - Oct'11 13
14. Function prototypes
(function argument checking is optional)
/* avoid these mistakes – use a compiler option that enforces C++ rules */
int g(int); /* prototype – like C++ function declaration */
int h(); /* not a prototype – the argument types are unspecified */
int f(p,b) char* p; char b; /* old style definition – not a prototype */
{ /* … */ }
int my_fct(int a, double d, char* p) /* new style definition – a prototype */
{
f(); /* ok by the compiler! But gives wrong/unexpected results */
f(d,p); /* ok by the compiler! But gives wrong/unexpected results */
h(d); /* ok by the compiler! But may give wrong/unexpected results */
ff(d); /* ok by the compiler! But may give wrong/unexpected results */
g(p); /* error: wrong type */
g(); /* error: argument missing */
}
Stroustrup/PPP - Oct'11 14
15. printf() – many people’s favorite C function
Format string
/* no iostreams – use stdio */
#include<stdio.h> /* defines int printf(const char* format, …); */
int main(void)
{
printf("Hello, worldn");
return 0; Arguments to be formatted
}
void f(double d, char* s, int i, char ch)
{
printf("double %g string %s int %i char %cn", d, s, i, ch);
printf("goof %sn", i); /* uncaught error */
}
Formatting characters
Format strings
Stroustrup/PPP - Oct'11 15
16. scanf() and friends
/* the most popular input functions from <stdio.h>: */
int i = getchar(); /* note int, not char;
getchar() returns EOF when it reaches end of file */
p = gets(); /* read 'n' terminated line into char array pointed to by p */
void f(int* pi, char* pc, double* pd, char* ps)
{ /* read into variables whose addresses are passed as pointers: */
scanf("%i %c %g %s", pi, pc, pd, ps);
/* %s skips initial whitespace and is terminated by whitespace */
}
int i; char c; double d; char s[100]; f(&i, &c, &d, s); /* call to assign to i, c, d, and s */
Don’t ever use gets() or scanf("%s")!
Consider them poisoned
They are the source of many security violations
An overflow is easily arranged and easily exploitable
Use getchar()
Stroustrup/PPP - Oct'11 16
17. printf() and scanf() are not type safe
double d = 0;
int s = 0;
printf("d: %d , s: %sn", d, s); /* compiles and runs
the result might surprise you */
“s” for “string”
“d” for “decimal”, not “double”
Though error-prone, printf() is convenient for built-in types
printf() formats are not extensible to user-defined types
E.g. no %M for My_type values
Beware: a printf () with a user-supplied format string is a cracker tool
Stroustrup/PPP - Oct'11 17
18. Arrays and pointers
Defined almost exactly as in C++
In C, you have to use them essentially all the time
because there is no vector, map, string, etc.
Remember
An array doesn’t know how long it is
There is no array assignment
use memcpy()
A C-style string is a zero-terminated array
Stroustrup/PPP - Oct'11 18
19. C-style strings
In C a string (called a C-string or a C-style string in C++
literature) is a zero-terminated array of characters
char* p = "asdf";
char s[ ] = "asdf";
p: 'a' 's' 'd' 'f' 0
s: 'a' 's' 'd' 'f' 0
Stroustrup/PPP - Oct'11 19
20. C-style strings
Comparing strings
#include <string.h>
if (s1 = = s2) { /* do s1 and s2 point to the same array?
(typically not what you want) */
}
if (strcmp(s1,s2) = = 0) { /* do s1 and s2 hold the same characters? */
}
Finding the lengths of a string
int lgt = strlen(s); /* note: goes through the string at run time
looking for the terminating 0 */
Copying strings
strcpy(s1,s2); /* copy characters from s2 into s1
be sure that s1 can hold that many characters */
Stroustrup/PPP - Oct'11 20
21. C-style strings
The string copy function strcpy() is the archetypical
C function (found in the ISO C standard library)
Unless you understand the implementation below,
don’t claim to understand C:
char* strcpy(char *p, const char *q)
{
while (*p++ = *q++);
return p;
}
For an explanation see for example K&R or TC++PL
Stroustrup/PPP - Oct'11 21
22. Standard function libraries
<stdio.h> printf(), scanf(), etc.
<string.h> strcmp(), etc.
<ctype.c> isspace(), etc.
<stdlib.h> malloc(), etc.
<math.h> sqrt(), etc.
Warning: By default, Microsoft tries to force you to use safer,
but non-standard, alternatives to the unsafe C standard library
functions
Stroustrup/PPP - Oct'11 22
23. Free store: malloc()/free()
#include<stdlib.h>
void f(int n) {
/* malloc() takes a number of bytes as its argument */
int* p = (int*)malloc(sizeof(int)*n); /* allocate an array of n ints */
/* … */
free(p); /* free() returns memory allocated by malloc() to free store */
}
Stroustrup/PPP - Oct'11 23
24. Free store: malloc()/free()
Little compile-time checking
/* malloc() returns a void*. You can leave out the cast of malloc(), but don’t
*/
double* p = malloc(sizeof(int)*n); /* probably a bug */
Little run-time checking
int* q = malloc(sizeof(int)*m); /* m ints */
for (int i=0; i<n; ++i) init(q[i]);
No initialization/cleanup
malloc() doesn’t call constructors
free() doesn’t call destructors
Write and remember to use your own init() and cleanup()
There is no way to ensure automatic cleanup
Don’t use malloc()/free() in C++ programs
new/delete are as fast and almostOct'11 better
Stroustrup/PPP - always 24
25. Uncast malloc()
The major C/C++ incompatibility in real-world code
Not-type safe
Historically a pre-standard C compatibility hack/feature
Always controversial
Unnecessarily so IMO
void* alloc(size_t x); /* allocate x bytes
in C, but not in C++, void* converts to any T* */
void f (int n)
{
int* p = alloc(n*sizeof(int)); /* ok in C; error in C++ */
int* q = (int*)alloc(n*sizeof(int)); /* ok in C and C++ */
/* … */
} Stroustrup/PPP - Oct'11 25
26. void*
Why does void* convert to T* in C but not in C++?
C needs it to save you from casting the result of malloc()
C++ does not: use new
Why is a void* to T* conversion not type safe?
void f()
{
char i = 0;
char j = 0;
char* p = &i;
void* q = p;
int* pp = q; /* unsafe, legal C; error in C++ */
*pp = -1; /* overwrite memory starting at &i */
}
Stroustrup/PPP - Oct'11 26
27. Comments
// comments were introduced by Bjarne Stroustrup into C++
from C’s ancestor BCPL when he got really fed up with typing
/* … */ comments
// comments are accepted by most C dialects including the new
ISO standard C (C99)
Stroustrup/PPP - Oct'11 27
28. const
// in C, a const is never a compile time constant
const int max = 30;
const int x; // const not initialized: ok in C (error in C++)
void f(int v)
{
int a1[max]; // error: array bound not a constant (max is not a constant!)
int a2[x]; // error: array bound not a constant (here you see why)
switch (v) {
case 1:
// …
case max: // error: case label not a constant
// …
}
} Stroustrup/PPP - Oct'11 28
29. Instead of const use macros
#define max 30
void f(int v)
{
int a1[max]; // ok
switch (v) {
case 1:
// …
case max: // ok
// …
}
}
Stroustrup/PPP - Oct'11 29
30. Beware of macros
#include "my_header.h"
// …
int max(int a, int b) { return a>=b?a:b; } // error: “obscure error message”
As it happened my_header.h contained the macro max from the previous
slide so what the compiler saw was
int 30(int a, int b) { return a>=b?a:b; }
No wonder it complained!
There are tens of thousands of macros in popular header files.
Always define macros with ALL_CAPS names, e.g.
#define MY_MAX 30
and never give anything but a macro an ALL_CAPS name
Unfortunately, not everyone obeys the ALL_CAPS convention
Stroustrup/PPP - Oct'11 30
31. C/C++ interoperability
Works because of shared linkage model
Works because a shared model for simple objects
built-in types and structs/classes
Optimal/Efficient
No behind-the-scenes reformatting/conversions
Stroustrup/PPP - Oct'11 31
32. Calling C from C++
Use extern "C" to tell the C++ compiler to use C calling
conventions
// calling C function from C++:
extern "C" double sqrt(double); // link as a C function
void my_c_plus_plus_fct()
{
double sr = sqrt(2);
// …
}
Stroustrup/PPP - Oct'11 32
33. Calling C++ from C
No special action is needed from the C compiler
/* call C++ function from C: */
int call_f(S* p, int i); /* call f for object pointed to by p with argument i */
struct S* make_S(int x, const char* p); /* make S( x,p) on the free store */
void my_c_fct(int i)
{
/* … */
struct S* p = make_S(17, "foo");
int x = call_f(p,i);
/* … */
} Stroustrup/PPP - Oct'11 33
34. Word counting example (C++ version)
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
map<string,int> m;
string s;
while (cin>>s) m[s]++; // use getline() if you really want lines
for(map<string,int>::iterator p = m.begin(); p!=m.end(); ++p)
cout << p->first << " : " << p->second << "n";
}
Stroustrup/PPP - Oct'11 34
35. Word counting example (C version)
// word_freq.c
// Walter C. Daugherity
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 1000 /* max unique words to count */
#define MAX_WORD_LENGTH 100
#define STR(s) #s /* macros for scanf format */
#define XSTR(s) STR(s)
typedef struct record{
char word[MAX_WORD_LENGTH + 1];
int count;
} record;
Stroustrup/PPP - Oct'11 35
36. Word counting example (C version)
int main()
{
// … read words and build table …
qsort(table, num_words, sizeof(record), strcmp);
for(iter=0; iter<num_words; ++iter)
printf("%s %dn",table[iter].word,table[iter].count);
return EXIT_SUCCESS;
}
Stroustrup/PPP - Oct'11 36
37. Word counting example (most of main)
record table[MAX_WORDS + 1];
int num_words = 0;
char word[MAX_WORD_LENGTH + 1];
int iter;
while(scanf("%" XSTR(MAX_WORD_LENGTH) "s", word) != EOF) {
for(iter = 0; iter < num_words && strcmp(table[iter].word, word); ++iter);
if(iter == num_words) {
strncpy(table[num_words].word, word, MAX_WORD_LENGTH + 1);
table[num_words++].count = 1;
}
else table[iter].count++;
if(num_words > MAX_WORDS){
printf("table is fulln");
return EXIT_FAILURE;
}
}
Stroustrup/PPP - Oct'11 37
38. Word counting example (C version)
Comments
In (some) colloquial C style (not written by BS)
It’s so long and complicated! (my first reaction – BS)
See, you don’t need any fancy and complicated language features!!!
(not my comment – BS)
IMHO not a very good problem for using C
Not an atypical application, but not low-level systems programming
It’s also C++ except that in C++, the argument to qsort() should be
cast to its proper type:
(int (*)(const void*, const void*))strcmp
What are those macros doing?
Maxes out at MAX_WORD words
Doesn’t handle words longer than MAX_WORD_LENGTH
First reads and then sorts
Inherently slower than the colloquial C++ version (which uses a map)
Stroustrup/PPP - Oct'11 38
39. More information
Kernighan & Ritchie: The C Programming Language
The classic
Stroustrup: TC++PL, Appendix B: Compatibility
C/C++ incompatibilities, on my home pages
Stroustrup: Learning Standard C++ as a New Language.
Style and technique comparisons
www.research.att.com/~bs/new_learning.pdf
Lots of book reviews: www.accu.org
Stroustrup/PPP - Oct'11 39