Showing posts with label CnCPP. Show all posts
Showing posts with label CnCPP. Show all posts

Thursday, 26 February 2015

Wildcard pattern matching in C

Welcome to Logically Proven blog.

This post demonstrates how to match a wildcard pattern against a particular string in C programming.

To achieve this we are using the function fnmatch which is in-built declared in the header fnmatch.h

Syntax:

int fnmatch (const char *pattern, const char *string, int flags)

This function tests whether the string is matching against the given pattern. This function returns zero if the string match with the given pattern else the function returns non-zero value FNM_NOMATCH.

The both  string and pattern are strings.

The third argument flags is a combination of flag bits that alter the details of matching which means you can change the way of matching the string by passing the flag bits.

The following are the available flags -

FNM_FILE_NAME

This flag treats the '/' character specially, for matching file names. If this flag is set, wildcard constructs in pattern cannot match '/' in string. Thus, the only way to match '/' is with an explicit '/' in pattern.

FNM_PERIOD

This flag treats the '.' character specially if it appears at the beginning of string. If this flag is set, wildcard constructs in pattern cannot match ‘.’ as the first character of string.

FNM_NOESCAPE

Don’t treat the ‘\’ character specially in patterns. Normally, ‘\’ quotes the following character, turning off its special meaning (if any) so that it matches only itself. When quoting is enabled, the pattern ‘\?’ matches only the string ‘?’, because the question mark in the pattern acts like an ordinary character.

If you use FNM_NOESCAPE, then ‘\’ is an ordinary character. 

FNM_LEADING_DIR

Ignore a trailing sequence of characters starting with a ‘/’ in string; that is to say, test whether string starts with a directory name that pattern matches.

If this flag is set, either ‘foo*’ or ‘foobar’ as a pattern would match the string ‘foobar/frobozz’.

FNM_CASEFOLD

Ignore case sensitive in comparing string to pattern.

FNM_EXTMATCH

Recognize beside the normal patterns also the extended patterns introduced in ksh. The patterns are written in the form explained in the following table where pattern-list is a | separated list of patterns.

?(pattern-list)
          matches any single character in the pattern-list

*(pattern-list)
          matches everything in the pattern-list

+(pattern-list)
          matches one or more occurrences of  any of the patterns in the pattern-list

@(pattern-list)
          matches exactly one occurrence of the patterns in the pattern-list

!(pattern-list)
          matches if input string is not matches the patter-list

[seq](pattern-list)
          matches the given sequence of the patterns in the pattern-list

[!seq](pattern-list)
          matches if input string is not matches the given sequence of the patterns in the pattern-list


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.


Logically Proven
Learn, Teach, Share


Ref: GNU C Library

Different modes of rounding float values in C and C++

Welcome to Logically Proven blog.

This post demonstrates different modes of rounding float values in C/C++ programming.

Floating-point calculations are carried out internally with extra precision, and then rounded to fit into the destination type.

ROUNDING MODES:

IEEE 754 defines the following four possible rounding modes:

1. Round to nearest (FE_TONEAREST)
2. Round toward plus infinity (FE_UPWARD)
3. Round toward minus infinity (FE_DOWNWARD)
4. Round toward zero (FE_TOWARDZERO)

RETURN VALUES:

You can decide the following destination types when rounding the float values -

These functions are available in the header #include <math.h>
So don't forget to include this header file while working with rounding the float values.

rint() - this function returns the integral value depending on rounding mode.

Syntax:

//x is the float value
double rint(double x)

If x is +/- infinity, rint() returns x.
If x is NaN, NaN is returned.

rintf() - this function returns the single-precision value depending on rounding mode.

Syntax:

//x is the float value
float rint(float x)

#include <fenv.h>

All these rounding modes are defined in the header file #include <fenv.h> as shown below -

/* FPU control word rounding flags */
#define FE_TONEAREST 0x0000   //decimal value: 0
#define FE_DOWNWARD 0x0400   //decimal value: 1024
#define FE_UPWARD 0x0800   //decimal value: 2048
#define FE_TOWARDZERO 0x0c00   //decimal value: 3072

The macro values may change depending on compiler.
The decimal representation of hex values are useful while setting the rounding mode. This is explained in the later section.

Now we look into each rounding mode.

Round to nearest (FE_TONEAREST):

This is the default mode. In this mode results are rounded to the nearest representable value. If the result is midway between two representable values, the even representable is chosen. Even here means the lowest-order bit is zero. This rounding mode prevents statistical bias and guarantees numeric stability.

Round toward plus infinity (FE_UPWARD):

All results are rounded to the smallest representable value which is greater than the result. In other words the values are rounded towards +infinity.

Round toward minus infinity (FE_DOWNWARD):

All results are rounded to the largest representable value which is less than the result. In other words the values are rounded towards -infinity.

Round toward zero (FE_TOWARDZERO):

All results are rounded to the largest representable value which is less than the result. In other words, if the result is negative it is rounded up; if it is positive, it is rounded down.

Important note - If the result is too small to be represented, it is rounded to zero. However, the sign of the result is preserved.

E.g. FE_TOWARDZERO(-0.22) returns -0.

This is because the negative zero can also result from some operations on infinity, such as 4/-infinity.

Get and Set Rounding Mode:

int fegetround(void) - This function is used to to return the currently selected rounding mode.

int fesetround(int round) -

This function is used to set the one of the rounding modes. The argument 'round' to this function is either an decimal representation or macro name (e.g. FE_UPWARD) of rounding mode. This function returns non-zero value if it fails to set rounding mode else zero if success.

Note - Avoid changing the rounding mode if possible. It can be expensive operation which leads to run the code slower than expected. For more details see your compiler documentation.

C Example:

#include <stdio.h>
#include <stdlib.h>
#include <fenv.h>
#include <math.h>

int main()
{
    float fValue;
    fValue = 10.22;
    
    //by default FE_TONEAREST
    printf("\nFE_TONEAREST:%f\n",rintf(fValue));

    //set to FE_UPWARD, returns zero if success
    //set using macro name
    printf("Set to FE_UPWARD: %d\n",fesetround(FE_UPWARD));
    printf("Currently the rounding mode is :%d\n",fegetround());
    printf("FE_TOUPWARD(10.22):%f\n",rintf(fValue));

    //set to FE_DOWNWARD, returns zero if success
    //FE_DOWNWARD integral representation is 1024
    //set using integral representation of macro name
    printf("Set to FE_DOWNWARD: %d\n",fesetround(1024));
    printf("Currently the rounding mode is :%d\n",fegetround());
    printf("FE_DOWNUPWARD(10.22):%f\n",rintf(fValue));

    //set to FE_TOWARDZERO, returns zero if success
    printf("Set to FE_TOWARD: %d\n",fesetround(FE_TOWARDZERO));
    printf("Currently the rounding mode is :%d\n",fegetround());
    printf("FE_TOWARDZERO(-0.22):%f\n",rintf(-0.22));

    printf("Currently the rounding mode is :%d\n",fegetround());
    printf("FE_TOWARDZERO(1.22):%f\n",rintf(1.52));

    return 0;
}

/* output:
FE_TONEAREST:10.000000
Set to FE_UPWARD: 0
Currently the rounding mode is :2048
FE_TOUPWARD(10.22):11.000000
Set to FE_DOWNWARD: 0
Currently the rounding mode is :1024
FE_DOWNUPWARD(10.22):10.000000
Set to FE_TOWARD: 0
Currently the rounding mode is :3072
FE_TOWARDZERO(-0.22):-0.000000
Currently the rounding mode is :3072
FE_TOWARDZERO(1.22):1.000000
*/

C++ Example: Rounding is guaranteed only if #pragma STDC FENV_ACCESS ON is set.

Include header files fenv.h and math.h if you are using older versions of C++. C++11 version and later supports cfenv.h and cmath.h header files.

#include <iostream>
#include <string>
#include <cfenv>
#include <cmath>
int main()
{
#pragma STDC FENV_ACCESS ON
    std::fesetround(FE_DOWNWARD);
    std::cout << "rounding down: \n"              
              << "  rintf(2.8) = " << std::rint(2.8) << "\n\n";
}

/*output:
rounding down:
   rint(2.8) = 2
*/

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Wednesday, 25 February 2015

Sleep function in C

Welcome to Logically Proven blog.

This post demonstrates how to make your program wait for a period of time.

It is required to wait out program for a little span of time before executing some statements. For example in case waiting for Input/Output signals.

The function sleep gives a simple way to make the program wait for a short interval. If the program doesn't use signals, then you can use sleep function to wait reliably the specified interval.

Otherwise, sleep can return sooner if a signal arrives; if you want to wait for a given interval regardless of signals, use sleep.

The sleep function is declared in unistd.h

Syntax:

unsigned int sleep (unsigned int seconds)

The sleep function waits for seconds or until a signal is delivered, whichever happens first.

The sleep function returns either requested interval is over, it returns a value zero else because of deliver of a signal, it returns a non-zero (remaining time) in the sleep interval.

You can call sleep function again if the sleep returns a non zero value as long as signals arrive infrequently. If the signals are arriving in rapid - it is difficult to decide the wait time whether to shorten or lengthen the wait time.

On some systems, sleep can do strange things if your program uses SIGALRM explicitly.

On GNU systems, it is safe to use sleep function and SIGALRM in the same program, because sleep doesn't work by means of SIGALRM.

Example:

#include <time.h>
#include <stdio.h>
#include<windows.h> 
#include <conio.h>
 
int main()
{
 printf("before sleep() function\n");
 Sleep(10); //10 seconds
 printf("after 10 seconds");
 getch();
 return 0;
}

This program waits for 10 seconds before printing "after 10 seconds".


Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.


Logically Proven
Learn, Teach, Share

Ref: GNU C Library

Monday, 23 February 2015

How to read an entire line from input in C++

Welcome to Logically Proven blog.
This post demonstrates how to read an entire line from input in C++.

 The following example can read only a single word. The white-space terminates the input.

#include<iostream>
#include<string>
using namespace std;

int main()
{
 cout << "Please enter:\n";

 string s;
 cin>>s;
 
 cout << "You entered " << s << '\n';
}

/*Output: Please enter:
This program takes only a single word
You entered This
*/

Note that there is no explicit memory management and no fixed-size buffer that you could possible to overflow.

The following program reads an entire line.

#include<iostream>
#include<string>
using namespace std;

int main()
{
 cout << "Please enter:\n";

 string s;
 getline(cin,s);
 
 cout << "You entered " << s << '\n';
}

/* output: Please enter:
This program reads an entire line.
You entered This program reads an entire line.
*/

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Convert an integer (decimal) to string in C++

Welcome to Logically Proven blog.
This post demonstrates how to convert an integer to a string in C++.

There are two ways to achieve this functionality.

1) using stringstream
2)using to_string function (C++ 11)

Using stringstream: (better if you are not using latest version)

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

 string itos(int i) // convert int to string
 {
  stringstream s;
  s << i;
  return s.str();
 }

 int main()
 {
  int i = 128;
  string ss= itos(i);
  const char* p = ss.c_str();

  cout << ss << " " << p << "\n";
 }

This technique works for converting any type that you can output using <<.

Using to_string function:

Converts a numerical value to std::string

The following functions are available in string library since C++ 11 version to convert numeric to string .

std::string to_string(int value); //converts a signed decimal to string
std::string to_string(long value); //converts a signed long decimal to string
std::string to_string(long long value); //converts a signed long long decimal to string
std::string to_string(unsigned value); //converts an unsigned decimal to string
std::string to_string(unsigned long value); //converts an unsigned long decimal to string
std::string to_string(unsigned long long value); //converts an unsigned long long decimal to string
std::string to_string(float value); //converts a float value to string
std::string to_string(double value); //converts double float value to string
std::string to_string(long double value); //converts long double float value to string

These functions takes 'value' as a parameter and returns a string equivalent.

Example:

#include <iostream>
#include <string>
 
int main() 
{
    double dVal = 28.28;
    std::string d_str = std::to_string(dVal);
    std::cout << d_str << '\n';
}

//output: 28.280000

You may run into some errors in the second case if your compiler doesn't support. The error message is
"to_string is not a member of std".  In this case please follow this link how to fix -
http://stackoverflow.com/questions/12975341/to-string-is-not-a-member-of-std-says-so-g

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven
Learn, Teach, Share

Pure virtual function in C++

Welcome to Logically Proven blog.

This post demonstrates "Pure Virtual Function" in C++.

A pure virtual function is a function that must be overridden in a derived class and need not to be defined.
A virtual function is declared to be "pure" using the curious "=0" syntax.

For example:

class Base {
 public:
  void f1();  // not virtual
  virtual void f2(); // virtual, not pure
  virtual void f3() = 0; // pure virtual
 };

 Base b; // error: pure virtual f3 not overridden

If a class is having any pure virtual functions, then the class is called "abstract class". Thus Base is an abstract class. So no objects are created directly for the class Base.

class Derived : public Base {
  // no f1: fine
  // no f2: fine, we inherit Base::f2
  void f3();
 };

 Derived d; // ok: Derived::f3 overrides Base::f3

Abstract classes are very useful for defining interfaces. Interface contains only method declarations. The classes which extends interface must contain method implementations. In fact, a class with only pure virtual functions is often called an interface.

If you don't override a pure virtual function in a derived class, that derived class becomes abstract.

class D2 : public Base {
  // no f1: fine
  // no f2: fine, we inherit Base::f2
  // no f3: fine, but D2 is therefore still abstract
 };

 D2 d; // error: pure virtual Base::f3 not overridden

Here D2 doesn't contain method implementation for function f3. So D2 is also an abstract class and no object is created. So in this context, classes Base and D2 are abstract classes.

In the below example class D3 is derived from the class D2 and contain implementation for the function f3. So we can create object successfully for the derived class D3.


class D3 : public D2 {
  // no f1: fine
  // no f2: fine, we inherit D2::f2
  void f3();
 };

 D3 d; // ok: D3::f3 overrides D2::f3

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

Tuesday, 17 February 2015

Calculate elapsed time - C Programming

Welcome to Logically Proven Blog.

This post teaches you how to measure the time taken by a function or a set of statements or a complete program.

It is very important to track the performance of our own application in certain cases where the execution time of a program plays a major role.

To calculate time taken by a process, we use clock() function which is available in a system library time.h. We can make use of available function in this library to calculate the elapsed time of a program.

For example,we want to calculate the execution time of a program, we can call the clock functions at the beginning and at the end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time.

Syntax:
#include <time.h>
 
clock_t start, end;
double elapsed_used;
 
start = clock();
... /* Do your work. */
end = clock();
elapsed_used = ((double)(end - start)) / CLOCKS_PER_SEC;
Example:
#include <stdio.h>
#include <time.h>
 
// A function that terminates when enter key is pressed
void funElapsedTime()
{
 printf("START \n");
 printf("Press enter to stop \n");
 while (1)
 {
  if (getchar())
   break;
 }
 printf("END \n");
}
 
// The main program calls function and calculates the elapsed time
int main()
{
 clock_t start,end;
 start = clock();
 funElapsedTime();
 end = clock();
 //calculate elapsed time
 double elapsed_time = ((double)(end-start)) / CLOCKS_PER_SEC; // in seconds
 
 printf("funElapsedTime took %f seconds to execute \n", elapsed_time);
 return 0;
}
 
 
/*output: START
          Press enter to stop
 
          END
   funElapsedTime took 5.010000 seconds to execute */
So you can include these clock functions anywhere in the program that you want to calculate the elapsed time.

Ref: http://www.gnu.org/software/libc/manual/html_node/CPU-Time.html

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

File Inclusion and difference between #include "file" and #include

Welcome to Logically Proven Blog.

This post teaches you file inclusion in your ‘C’ application and the difference between #include “file” and #include <file>

File inclusion is an important preprocessor directive of C programming. This directive causes one file to be included in another.

Syntax:

#include "filename"

It causes the entire contents of filename to be inserted into the source code at that point in the program.

We can use the file inclusion for the following benefits –
  • If we have a large program, divide the code into set of related functions to understand and organize your code in a better way. This increases readability of your code.
  • One more benefit of using file inclusion is re-usability. For example we need some macro definitions that requires in all programs that are commonly used. In this case store these macro definitions in a file and just include the file into your application.
The files that are included to have a ‘.h’ extension. The extension stands for “header file”. This header file contains C function declarations and macro definitions and to be shared between several source files.  There are two types – user header files (programmer writes) and compiler header files (that comes with the compiler).

For example, stdio.h header file, this comes along with your compiler.

The related library functions are grouped into different categories and then stored in different header files. For example all mathematical related functions are stored in the header file math.h.

The #include directive works by directing the C preprocessor to scan the specified file as input before continuing with the rest of the current file. Look at the following example to know how the preprocessor processes the #include directives.

For example, if you have a header file header.h as follows,

char *test(void);

and a main program called program.c that uses the header file, like this -

int x;
#include "header.h"
 
int main(void)
{
 puts(test());
 return 0;
}

the compiler will see the same token stream as it would if program.c read

int x;
char *test(void);
 
int main(void)
{
 puts(test());
 return 0;
}


Difference between #include “file” and #include <file>

There are two ways to write #include statement in your program.

#include "filename"
#include <filename>

#include “filename”

This command would look for the file “filename” in the current directory as well as the specified list of directories as mentioned in the include search path (compilers can be set up by selecting directories from the options menu, e.g., Turbo C/C++ compiler) that might have been set up.

#include <filename>

This command would look for the file “filename” in the specified list of directories only.

Please write your comments if you find anything is incorrect or do you want to share more information about the topic discussed above.

Logically Proven,
Learn, Teach, Share

Thursday, 5 February 2015

'undef' and 'pragma' directives - 'C' Programming

Welcome to Logically Proven blog.

This post teaches you the C preprocessor directives which are not very commonly used. They are

1. #undef
2. #pragma

To understand these directives, you must know what is a macro and ifdef directives. If you don't know please have a look into the previous post in this blog.

#undef directive

At certain times, it may necessary to cause the defined name to become "undefined". This can be accomplished by using the directive "#undef". 

In order to undefine a macro that has been earlier defined.

Syntax: #undef macro template

Example: 
#include <stdio.h>
#define INTEL
int main()
{
#undef INTEL //undefined the INTEL directive
#ifdef INTEL
 printf("INTEL code\n");
#else
 printf("Other than INTEL\n");
#endif
 
printf("Common code");
 
return 0;
}
 
/* Output: Other than INTEL
           Common code
*/
In this example, even though you defined the INTEL directive before main function, the compiler executes the statement in the else "Other than INTEL" because we are undefined the INTEL directive. The #undef directive cause the definition of INTEL to be removed from the system.

All subsequent #ifdef INTEL statements evaluate to FALSE. 

#pragma directive

This directive is another special-purpose directive that you can use to turn on or off certain features. For example you can use this directive often when you want to run some statements before the main function, before terminating the program and also to format, suppress warnings etc.

Pragmas vary from one compiler to another. 

In case of  Microsoft C compiler that deal with formatting source listings and placing comments in the object file generated by the compiler. 

Turbo C/C++ compiler has got a pragma that allows you yo suppress warnings generated by a compiler.

We will see these pragmas and how we can make use of.

(a) #pragma startup and #pragma exit
         These directives allow us to specify functions that are called before main() or just before the program terminates. 

Example:
#include <stdio.h>
 
void Intialize();
void CleanUp();
 
#pragma startup Intialize
#pragma exit CleanUp
 
int main()
{
 printf("\nInside main");
}
 
void Intialize()
{
 printf("\nBefore Main");
}
 
void CleanUp()
{
 printf("\nBefore Exit");
}
 
/* Output:  Before Main
     Inside main
     Before Exit
*/
Note: The functions Initialize() and CleanUp() should neither receive nor return any value. 

(b) Prioritized Pragmas:
         If you want two functions to get executed at start-up, then their pragmas should be defined in the reverse order or you can mention the priorities of the directives to decide which one should run first.

Syntax:
#pragma startup [priority]
#pragma exit [priority]
Where priority is optional integral number.
For user, priority varies from 64 to 255.
For C libraries, priority varies from 0 to 63.
Default priority is 100.

startup:
Lower value - Higher priority (executes first).
Higher value - Lower Priority (executes last).

exit:
Higher value - Higher priority (executes first).
Lower value - Lower priority (executes last).

Example:
#include <stdio.h>
 
void Function1();
void Function2();
#pragma startup Function1 123
#pragma startup Function2       //default priority - 100
#pragma exit Function2          //default priority - 100
#pragma exit Function1 123
 
int main()
{
 printf("\nInside main");
 return 0;
}
 
void Function1()
{
 printf("\nInside Function1");
}
 
void Function2()
{
 printf("\nInside Function2");
}
 
/* Output:
 Inside Function2
 Inside Function1
 Inside main
 Inside Function1
 Inside Function2
*/
(c) #pragma warn
     This directive tells the the compiler whether to suppress a specific warning or not.
Some warn pragmas -
#pragma warn -rvl //return value
#pragma warn -par   //parameter not used
#pragma warn -rch   //unreachable code
The minus sign (-) is to suppress the warnings and plus sign (+) is to flash the warnings on compilation.

Example -
int function1() //no return value
{
 int a = 5;
}
 
void function2(int x) //parameter not used
{
 printf("\nInside f2");
}
 
int function3() //unreachable code
{
 int x = 6;
 return x;
 x++;
}
 
int main()
{
 function1();
 function2(7);
 function3();
 return 0;
}
If you add these pragmas with minus sign, all these warnings will be suppressed on compilation. 
It is a bad practice to suppress warnings but at times it becomes useful to suppress them.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Logically Proven
learn, teach, share

Wednesday, 28 January 2015

Macros - Features of C Preprocessor

Welcome to Logically Proven Blog.
This post teaches you one of the important features of C preprocessor - Macro Expansion.

C preprocessor is a special program that processes source program before it is passed to the compiler. The preprocessor commands also known as directives. Each of these preprocessor directives begin with a # symbol. These directives can be placed anywhere in a source program but are most often placed at the beginning of a source program.

A million dollar question - Why Macro?
To made the program easier to read and understand.


Macro:

Have a look at the following program.
#include <stdio.h>
#define max 100
int main()
{
 printf("max is %d", max);
 return 0;
}
// Output: max is 100
// Note that the max inside "" is not replaced

In this program instead of writing 100 in the printf statement we are writing in the form of max, which has already defined before main() through the statement,
#define max 100
This statement is called macro. 

When we use define for a constant, the preprocessor produces a C program where the defined constant is searched and matching tokens are replaced with the given expression. In the above program max is defined as 100.


A #define directive could be used even to replace a condition as shown below -
#include <stdio.h>
#define AND &&
#define ARANGE ( a > 25 AND a < 50 )
int main()
{
 int a = 30;
 if (ARANGE)
  printf("within range");
 else
  printf("out of range");
 
 return 0;
}
// Output: within range
Note:
1. Macro template and macro expansion are separated by blanks or tabs.
2. A macro definition is never to be terminated by a semicolon.

Macro with Arguments:

The macros can take arguments like function, the arguments are not checked for data type, For example, the following macro INCREMENT(x) can be used for x of any data type.

#include <stdio.h>
#define INCREMENT(x) ++x
int main()
{
 char *ptr = "LogicallyProven";
 int x = 10;
 printf("%s  ", INCREMENT(ptr));
 printf("%d", INCREMENT(x));
 return 0;
}
// Output: ogicallyProven 11
An another example of macro with arguments which is checking for a condition -

#define ISDIGIT(x) ( x >= 48 && x <= 57 )

Note:

1. Do not leave a blank between the macro template and its argument while defining the macro.
    For example there is no blank between ISDIGIT and (x) in the definition above.

2. The entire macro expansion should be enclosed within parantheses.
     Consider a statement in a program: i= 64/SQUARE(4)

     Macro:    #define SQUARE(n) n*n        - Wrong  //output is 64 (64/4*4)
                      #define SQUARE(n) (n*n)      - Correct //output is 4 (64/(4*4))

     The macro arguments are not evaluated before macro expansion.


     This can be corrected using "inline functions".
   
   inline int square(int n) { return n*n; }
   int main()
   {
      int n = 64 / square(4);
      printf("%d", n);
      return 0;
   }
   // Output: 4

3. The macro can be written in multiple lines using '\'. The last line doesn't need to have '\'.

     Example:
                     #include <stdio.h>
            #define PRINT(i, limit) while (i < limit) \
                      { \
                             printf("GeeksQuiz "); \
                             i++; \
                      }
Token-Pasting operator:

The tokens passed to macros can be concatenated using operator ## called token-pasting operator.

#include <stdio.h>
#define merge(a, b) a##b
int main()
{
 printf("%d ", merge(12, 34));
}
// Output: 1234
String converter:

A token passed to macro can be converted to a string by appending # before it.
#include <stdio.h>
#define get(a) #a
int main()
{
 // LogicallyProven is changed to "LogicallyProven"
 printf("%s", get(LogicallyProven));
}
// Output: LogicallyProven
Standard macros:

There are some standard macros which can be used to print the program file, date of compilation, time of compilation and line number in C code.

#include <stdio.h>
int main()
{
 printf("Current File :%s\n", __FILE__);
 printf("Current Date :%s\n", __DATE__);
 printf("Current Time :%s\n", __TIME__);
 printf("Line Number :%d\n", __LINE__);
 return 0;
}
 
/* Output:
Current File :D:\myCB\ifcondition\LogicallyProven\main.c
Current Date :Jan 28 2015
Current Time :17:45:45
Line Number :7 */

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Logically Proven
learn, teach, share

 
biz.