Quantcast
Channel: Mandalika's scratchpad
Viewing all articles
Browse latest Browse all 115

Programming in C: Few Tidbits #8

$
0
0

1) Function Pointers

Similar to a variable declared as pointer to some data type, a variable can also be declared to be a pointer to a function. Such a variable stores the address of a function that can later be called using that function pointer. In other words, function pointers point to the executable code rather than data like typical pointers.

eg.,

void (*func_ptr)();

In the above declaration, func_ptr is a variable that can point to a function that takes no arguments and returns nothing (void).

The parentheses around the function pointer cannot be removed. Doing so makes the declaration a function that returns a void pointer.

The declaration itself won't point to anything so a value has to be assigned to the function pointer which is typically the address of the target function to be executed.

If a function by name dummy was already defined, the following assignment makes func_ptr variable to point to the function dummy.

eg.,

void dummy() { return; }
func_ptr = dummy;

In the above example, function's name was used to assign that function's address to the function pointer. Using address-of or address operator (&) is another way.

eg.,

void dummy() { return; }
func_ptr = &dummy;

To be continued ..

2) Printing Unicode Characters

Here's one possible way.

  • Make use of wide characters. Wide character strings can represent Unicode character value (code point).
  • The standard C library provides wide-character functions. Include the header file wchar.h
  • Set proper locale to support wide characters
  • Print the wide character(s) using standard printf and "%ls" format specifier -or- using wprintf to output formatted wide characters

Following rudimentary code sample prints random currency symbols and a name in Telugu script using both printf and wprintf function calls.


% cat -n unicode.c
1 #include <wchar.h>
2 #include <locale.h>
3 #include <stdio.h>
4
5 int main()
6 {
7 setlocale(LC_ALL,"en_US.UTF-8");
8 wprintf(L"\u20AC\t\u00A5\t\u00A3\t\u00A2\t\u20A3\t\u20A4");
9 wchar_t wide[4]={ 0x0C38, 0x0C30, 0x0C33, 0 };
10 printf("\n%ls", wide);
11 wprintf(L"\n%ls", wide);
12 return 0;
13 }

% cc -o unicode unicode.c

% ./unicode
€ ¥ £ ¢ ₣ ₤
సరళ
సరళ

Here is one website where numerical values for various Unicode characters can be found.


Viewing all articles
Browse latest Browse all 115

Trending Articles