Translate

ads

Showing posts with label C. Show all posts
Showing posts with label C. Show all posts

1 Aug 2019

Is it fine to jot down “void main()” or “main()” in C/C++?

Is it fine to jot down “void main()” or “main()” in C/C++?


c



Is it fine to jot down “void main()” or “main()” in C/C++?

wordpress



is not and ne'er has been C++, nor has it even been C. See the ISO C++ commonplace 3.6.1[2] or the ISO C commonplace 5.1.2.2.1. A conforming implementation accepts




html


and


css



A conforming implementation might give a lot of versions of main(), however they have to all have come back type int. The int returned by main() could be a method for a program to come back a value to “the system” that invokes it. On systems that doesn’t give such a facility the come back value is neglected, however that doesn’t build “void main()” legal C++ or legal C. even if your compiler accepts “void main()” avoid it, or risk being thought-about ignorant by C and C++ programmers.
In C++, main() needn't contain a certain come back statement. in this case, the value came back is 0, which means productive execution.


example:


javascript

Note also that neither ISO C++ nor C99 permits you to go away the kind out of a declaration. That is, in distinction to C89 and ARM C++ ,”int” isn't assumed wherever a type is missing in an exceedingly declaration. Consequently


book


31 Jul 2019

int (1 sign bit + 31 data bits) in C


int (1 sign bit + 31 data bits)  in C
Book



In C programing language a commonest keyword ‘int’ is employed to outline any positive or negative number. however there's a distinction between an integer and also the numbers which may be depicted with the assistance of the keyword ‘int’. Not each integer will be depicted with the keyword ‘int’. in keeping with MinGW the scale of 1 ‘int’ is 4 bytes that is adequate 32 bits (1 byte=8 bits). it's still a story somewhere that ‘int’ will represent an integer or ‘int’ is employed to represent integers. number could be a terribly huge class of numbers wherever joined ‘int’ has restricted and actual quantity of memory (size of ‘int’ is 4 bytes or 32 bits) to store what's being depicted by it. an ‘int’ sort variable in C language is ready to store solely numbers until 2147483647. on the far side this variety ‘int’ fails to store exactly and even not properly. ‘int’ could be a 32 bit knowledge sort. Whenever variety is being assigned to an ‘int’ sort variable, it's initial converted to its binary illustration (that is in 0’s and 1’s) then it's unbroken in memory at specific location. associate degree ‘int’ is really one sign bit + 31 data bits, that's thirty one bits are accessible for storing the quantity being appointed to a ‘int’ sort variable and one bit is reserved for maintaining the sign of the quantity that is either + or – . The sign is additionally depicted by binary digits, 0 for positive sign and 1 for negative sign


Example – Consider

C



At now 1st 2147483647 are regenerate into its binary kind that is equal to:

1111111111111111111111111111111.

1111111111111111111111111111111 could be a 31 digit binary number can|which can|which could be able to} be assigned to variable num’s right most 31 bits and also the 32nd bit will have a zero(0) because the number being assigned to variable num is a positive variety. If we Associate in Nursingd} store any variety larger than 2147483647 into an ‘int’ sort variable then we are going to lose data.




27 Jun 2019

Signals in C language


Signals in C language




Prerequisite : Fork system call, Wait call
A signal could be a software package generated interrupt that's sent to a process by the OS attributable to once user press ctrl-c or another method tell one thing to the present method.
There area unit fix set of signals which will be sent to a method. signal area unit known by integers.
Signal variety have symbolic names. as an example SIGCHLD is variety of the signal sent to the parent method once kid terminates.
Examples:



#define SIGHUP  1   /* Hangup the process */
#define SIGINT  2   /* Interrupt the process */
#define SIGQUIT 3   /* Quit the process */
#define SIGILL  4   /* Illegal instruction. */
#define SIGTRAP 5   /* Trace trap. */
#define SIGABRT 6   /* Abort. */




  ü OS Structures for Signals

For each method, the operating system maintains two integers with the bits resembling a signal numbers.
The two integers keep track of: unfinished signals and blocked signals




Example : 

In the example below, the intelligence operation ( = 2) signal is blocked and no signals are unfinished.

Pending Signals :

   31         30      29         28      ......       3           2          1           0
0
0
0
0
……
0
0
0
0


Blocked Signals :

    31         30      29         28      ......       3           2          1           0
0
0
0
0
……
0
0
0
0


A signal is distributed to a process setting the corresponding bit within the unfinished signals number for the process. anytime the OS selects a method to be run on a processor, the unfinished and blocked integers ar checked. If no signals ar unfinished, the method is restarted commonly and continues death penalty at its next instruction.


If 1 or additional signals ar unfinished, however all is blocked, the method is also restarted commonly however with the signals still marked as unfinished. If one or additional signals ar unfinished and NOT blocked, the OS executes the routines within the process’s code to handle the signals.

Default Signal Handlers

There are many default signal handler routines. every signal is related to one amongst these default handler routine. the various default handler routines generally have one amongst the subsequent actions:

  Ø  Ign: Ignore the signal; i.e., do nothing, simply come back
  Ø  Term: terminate the method
  Ø  Cont: unblock a stopped method
  Ø  Stop: block the method



// CPP program to illustrate 
// default Signal Handler 
#include<stdio.h> 
#include<signal.h> 

int main() 

signal(SIGINT, handle_sigint); 
while (1) 

printf(“hello world\n”); 
sleep(1); 

return 0; 



Output: Print hello world infinite times. If user presses ctrl-c to terminate the process because of SIGINT signal sent and its default handler to terminate the process.


hello world
hello world
hello world

terminated

User outlined Signal Handlers

A method will replace the default signal handler for nearly all signals (but not SIGKILL) by its user’s own handler perform.
A signal handler perform will have any name, however should have return sort void and have one int parameter.
Example: you would possibly opt for the name sigchld_handler for a signal handler for the SIGCHLD signal (termination of a toddler process). Then the declaration would be:




void sigchld_handler(int sig);




When a symbol handler executes, the parameter passed to that is that the range of the signal. A applied scientist will use identical signal handler operate to handle many signals. during this case the handler would wish to ascertain the parameter to examine that signal was sent. On the opposite hand, if a symbol handler function solely handles one signal, it isn’t necessary to hassle examining the parameter since it'll continuously be that signal number.

// CPP program to illustrate 
// User-defined Signal Handler 
#include<stdio.h> 
#include<signal.h> 

// Handler for SIGINT, caused by 
// Ctrl-C at keyboard 
void handle_sigint(int sig) 

printf("Caught signal %d\n", sig); 


int main() 

signal(SIGINT, handle_sigint); 
while (1) ; 
return 0; 




^CCaught signal 2  // when user presses ctrl-c
^CCaught signal 2

Sending signals via kill()
We can send a signal using kill() to the process

int kill(pid_t pid, int signal);
pid: id of destination process
signal: the type of signal to send

Return value: 0 if signal was sent successfully

Example :

pid_t iPid = getpid(); /* Process gets its id.*/
kill(iPid, SIGINT);  /* Process sends itself a  SIGINT signal  
(commits suicide?)(because of SIGINT
signal default handler is terminate the process) */
        

1. What is the Output of the following program?

#include<stdio.h>
#include<wait.h>
#include<signal.h>
int main()
{
            int stat;
            pid_t pid;
            if ((pid = fork()) == 0)
                        while(1) ;
            else
            {
                        kill(pid, SIGINT);
                        wait(&stat);
                        if (WIFSIGNALED(stat))
                                    psignal(WTERMSIG(stat), "Child term due to");
            }
}


Output:

 Child term due to: Interrupt

2. What is the Output of the following program?

#include<stdio.h>
#include<signal.h>
#include<wait.h>
int val = 10;
void handler(int sig)
{
val += 5;
}
int main()
{
pid_t pid;
signal(SIGCHLD, handler);
if ((pid = fork()) == 0)
{
val -= 3;
exit(0);
}
waitpid(pid, NULL, 0);
printf("val = %d\n", val);
exit(0);

}



val = 15


3. Consider the following code. What is the output?

void handler2(int sig) 
counter += 3; 
printf("counter = %d\n", counter); 
exit(0); 

int main() 
pid_t p; 
int status; 
signal(SIGUSR1, handler1); 
if ((pid = fork()) == 0) 
signal(SIGUSR1, handler2); 
kill(getppid(), SIGUSR1); 
while(1) ; 
if ((p = wait(&status)) > 0) 
counter += 4; 
printf("counter = %d\n", counter); 

Output

counter = 1         //(parent’s handler)
counter = 3         //(child’s handler)
counter = 5         //(parent’s main)

Difference between while(1) and while(0) in C language

Difference between while(1) and while(0) in C language



In most programing languages, a jiffy loop may be a control flow statement that enables code to be executed repeatedly supported a given mathematician condition. The mathematician condition is either true or false

while(1)

It is Associate in Nursing infinite loop which can run until a prospect statement is issued expressly. apparently not while(1) however any number that is non-zero can provide the similar result as while(1). Therefore, while(1), while(2) or while(-255), all can provide infinite loop only.

while(1) or while(any non-zero integer)
    // loop runs infinitely
}


A simple usage of while(1) will be within the Client-Server program. within the program, the server runs in an infinite whereas loop to receive the packets sent type the purchasers.But much, it's not advisable to use while(1) in realworld as a result of it will increase the computer hardware usage and additionally blocks the code i.e one cannot start from the while(1) till the program is closed manually.while(1) will be used at an area wherever condition has to be true continually

while(1) is used at an area wherever condition must be true always

// C program to illustrate while(1) 
int main() 
int i = 0; 
while ( 1 ) 
printf( "%d\n", ++i ); 
if (i == 5)  
break; // Used to come 
// out of loop 
return 0; 

1
2
3
4
5

while(0)

It is opposite of while(1). It suggests that condition can perpetually be false and therefore code in whereas can never get executed.

while(0)
{
    // loop does not run
}


// C program to illustrate while(0) 
int main() 
int i = 0, flag=0; 
while ( 0 ) 
// This line will never get executed 
printf( "%d\n", ++i ); 
flag++; 
if (i == 5) 
break; 
if (flag==0) 
printf ("Didn't execute the loop!"); 
return 0; 


Output:

Didn't execute the loop!


C programming language commonplace


C programming language commonplace



The idea of this text is to introduce C commonplace.What to try and do once a program produces different|completely different} results in 2 different compilers?
For example, consider the subsequent easy program.


void main()

The above program fails in sayed 360 because the come style of main is void, however it compiles in Turbo C. however will we decide whether or not it's a legitimate c program or not?

Consider the subsequent program as another example. It produces completely different|completely different} results in different compilers.



#include<stdio.h> 
int main() 

int i = 1; 
printf("%d %d %d\n", i++, i++, i); 
return 0; 



2 1 3 - using g++ 4.2.1 on Linux.i686
1 2 3 - using SunStudio C++ 5.9 on Linux.i686
2 1 3 - using g++ 4.2.1 on SunOS.x86pc
1 2 3 - using SunStudio C++ 5.9 on SunOS.x86pc
1 2 3 - using g++ 4.2.1 on SunOS.sun4u
1 2 3 - using SunStudio C++ 5.9 on SunOS.sun4u
  


  Ø What is C standard?
The latest C standard is ISO/IEC 9899:2011, conjointly referred to as C11 because the final draft was revealed in 2011. Before C11, there was C99. The C11 final draft is offered here. See this for complete history of C standards.


  Ø  Can we all know behavior of all programs from C standard?

C standard leaves some behavior of the many C constructs as undefined and a few as some to modify the specification and permit some flexibility in implementation. for instance, in C the use of any automatic variable before it's been initialized yields undefined behavior and order of evaluations of sub expressions is some. This specifically frees the compiler to try and do no matter is best or most effective, ought to such a program be submitted.


  Ø  So what's the conclusion regarding higher than two examples?

Let us contemplate the primary example that is “void main() ”, the quality says following regarding example of main()



The function called at program startup is named main. The implementation
declares no prototype for this function. It shall be defined with a return
type of int and with no parameters:
       int main(void) { /* ... */ }
or with two parameters (referred to here as argc and argv, though any names
may be used, as they are local to the function in which they are declared):
       int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.





So the return type void doesn’t follow the quality and it’s one thing allowed by bound compilers.Let us mention second example. Note the subsequent statement in C standard is listed below unspecified behavior.



The order in which the function designator, arguments, and
subexpressions within the arguments are evaluated in a function
call (6.5.2.2).







  Ø  What to try and do with programs whose behavior is       indefinable or unspecified in standard?

As a programmer, it's ne'er a decent plan to use programming constructs whose behaviour is indefinable or unspecified , such programs should be discouraged. The output of such programs might modification with compiler and/or machine











27 May 2019

OVERVIEW OF c


OVERVIEW OF C



C could be a general, problem-oriented language that was originally developed by Dennis M. Ritchie to develop the UNIX systemsoftware package at Bell Labs. C was originally 1st enforced on the DEC PDP-11 pc in 1972.
In 1978, Brian Kernighan and Dennis Ritchie made the primary publically out there description of C, currently called the K&R commonplace.
The UNIX system software package, the C compiler, and primarily all UNIX system application programs are written in C. C has currently become a wide used skilled language for varied reasons:
Easy to be told
Structured language
It produces economical programs
It will handle low-level activities
It may be compiled on a spread of pc platforms



Facts regarding C

C was fancied to write down Associate in Nursing software package referred to as UNIX system.
C could be a successor of B language that was introduced round the early Seventies.
The language was formalized in 1988 by the yank National commonplace Institute (ANSI).
The UNIX system OS was altogether written in C.
Today C is that the most generally used and well-liked System artificial language.
Most of the progressive code are enforced mistreatment C.
Today's hottest UNIX system OS and RDBMS MySQL are written in C.


Why Use C?

C was at first used for system development work, notably the programs that make-up the software package. C was adopted as a system development language as a result of it produces code that runs nearly as quick because the code written in programing language. Some samples of the employment of C would possibly be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Print Spoolers
Network Drivers
Modern Programs
Databases
Language Interpreters
Utilities

C Programs
A programme will vary from three lines to ample lines and it ought to be written into one or a lot of text files with extension ".c"; for instance, hello.c. you'll use "vi", "vim" or the other text editor to write down your programme into a file.
This tutorial assumes that you just acumen to edit a document and the way to write down ASCII text file within a program file

26 May 2019

C Language Introduction

C Language Introduction



C may be a procedural artificial language. it absolutely was at the start developed by Dennis Ritchie between 1969 and 1973. it absolutely was in the main developed as a system artificial language to jot down OS. the most options of C language embody low-level access to memory, straightforward set of keywords, and clean vogue, these options create C language appropriate for system programming like OS or compiler development.
Many later languages have borrowed syntax/features directly or indirectly from C language. Like syntax of Java, PHP, JavaScript and lots of alternative languages is principally supported C language. C++ is sort of a superset of C language (There area unit few programs that will compile in C, however not in C++).

Beginning with C programming:

Structure of a C program
After the on top of discussion, we are able to formally assess the structure of a C program. By structure, it's meant that any program will be written during this structure solely. Writing a C program in the other structure can therefore result in a Compilation Error.



Header Files Inclusion: the primary and foremost element is that the inclusion of the Header files in an exceedingly C program.
A header file may be a file with extension .h that contains C operate declarations and macro definitions to be shared between many supply files.



Some of C Header files

stddef.h – Defines several useful types and macros.
stdint.h – Defines exact width integer types.
stdio.h – Defines core input and output functions
stdlib.h – Defines numeric conversion functions, pseudo-random network generator, memory allocation
string.h – Defines string handling functions
math.h – Defines common mathematical functions
Syntax to include a header file in C:

#include <(header_file_name).h>
Main Method Declaration: The next part of a C program is to declare the main() function. The syntax to declare the main function is:
Syntax to Declare main method:

int main()
{}

Variable Declaration: subsequent a part of any program is that the variable declaration. It refers to the variables that area unit to be utilized in the operate. Please note that in program, no variable may be used while not being declared. conjointly in an exceedingly program, the variables area unit to be declared before any operation within the operate.
Example:

int main()
{
    int a;
.
.

Body: Body of a operate in program, refers to the operations that area unit performed within the functions. It is something like manipulations, searching, sorting, printing, etc.
Example:


int main()
{
    int a;

    printf("%d", a);
.
.

Return Statement: The last half in any programme is that the come statement. The come statement refers to the returning of the values from a operate. This come statement and come worth depend on the return-type of the operate. as an example, if the come kind is void, then there'll be no come statement. In the other case, there'll be a come statement and therefore the come worth are of the sort of the required return-type.
Example:

int main()
{
    int a;

    printf("%d", a);

    return 0;
}



#include <stdio.h>
int main(void)
{
printf("GeeksQuiz");
return 0;
}

Let us analyze the command by line.
Line 1: [ #include ] during a C program, all lines that begin with # square measure processed by preprocessor that may be a program invoked by the compiler. during a} very basic term, preprocessor takes a C program and produces another C program. The created program has no lines beginning with #, all such lines square measure processed by the preprocessor. within the on top of example, preprocessor copies the preprocessed code of stdio.h to our file. The .h files square measure referred to as header files in C. These header files typically contain declaration of functions. we'd like stdio.h for the operate printf() employed in the program.





Line two [ int main(void) ] There should to be start line from wherever execution of compiled C program begins. In C, the execution usually begins with initial line of main(). The void written in brackets indicates that the most doesn’t take any parameter (See this for additional details). main() are often written to require parameters conjointly. we'll be covering that in future posts.
The int written before main indicates come back style of main(). the worth came by main indicates standing of program termination. See this post for additional details on come back sort.

Line three and 6: [ ] In C language, a try of frizzy brackets outline a scope and primarily employed in functions and management statements like if, else, loops. All functions should begin and finish with frizzy brackets.

Line four [ printf(“Sayed”); ] printf() may be a commonplace library operate to print one thing on commonplace output. The punctuation mark at the top of printf indicates line termination. In C, punctuation mark is often wont to indicate finish of statement.

Line five [ come back 0; ] The come back statement returns the worth from main(). The came worth could also be utilized by package to grasp termination standing of your program. the worth zero usually suggests that no-hit termination.

Linux: For UNIX operating system, gcc comes bundled with the UNIX operating system, Code Blocks may also be used with UNIX operating system.

Please write comments if you discover something incorrect, otherwise you wish to share additional data regarding the subject mentioned on top of